msdn给我们这个例子来检索post数据。
public static void ShowRequestData (HttpListenerRequest request)
{
if (!request.HasEntityBody)
{
Console.WriteLine("No client data was sent with the request.");
return;
}
System.IO.Stream body = request.InputStream;
System.Text.Encoding encoding = request.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
if (request.ContentType != null)
{
Console.WriteLine("Client data content type {0}", request.ContentType);
}
Console.WriteLine("Client data content length {0}", request.ContentLength64);
Console.WriteLine("Start of client data:");
// Convert the data to a string and display it on the console.
string s = reader.ReadToEnd();
Console.WriteLine(s);
Console.WriteLine("End of client data:");
body.Close();
reader.Close();
// If you are finished with the request, it should be closed also.
}source
我检查了Streamreader类,没有开始...结束..。方法。这是否意味着无法异步检索Post数据?或者在HttpListener的回调到来之前,它已经被检索到了?
我不想在一个慢速post数据块进来的时候得到线程停顿。
执行此操作的正确异步方式是什么?(或者ReadToEnd实际上是正确的?)
谢谢
R
发布于 2009-10-17 14:30:25
您可以在传入的流上调用Stream.BeginRead,而不是使用StreamReader。
更新:下面是一个在流上使用BeginRead的示例:
class State
{
public Stream Stream { get; set; }
public byte[] Buffer { get; set; }
}
class Program
{
private const int ChunkSize = 1024;
static void Main(string[] args)
{
var stream = new FileStream("test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var state = new State { Stream = stream, Buffer = new byte[ChunkSize] };
var ar = stream.BeginRead(state.Buffer, 0, state.Buffer.Length, Callback, state);
while (!ar.IsCompleted)
{
Thread.Sleep(10);
}
}
static void Callback(IAsyncResult ar)
{
var state = (State)ar.AsyncState;
var bytesRead = state.Stream.EndRead(ar);
if (bytesRead > 0)
{
byte[] buffer = new byte[bytesRead];
Buffer.BlockCopy(state.Buffer, 0, buffer, 0, bytesRead);
// Do something with the received buffer.
Console.Write(Encoding.UTF8.GetString(buffer));
state.Stream.BeginRead(state.Buffer, 0, state.Buffer.Length, Callback, state);
}
else
{
// reached the end of the stream
state.Stream.Dispose();
}
}
}https://stackoverflow.com/questions/1582309
复制相似问题