Reputation: 620
I have an issue caused by an external factor which is causing my app pool to queue up requests and hang. The issue seems to be caused when the client making the HTTP request somehow loses its TCP layer connection to my server, whilst the server is trying to read all the data POST'd to it.
I am using an Asynchronous HTTP handler, and I am using the following code to read all the posted data:
string post_data = new StreamReader(context.Request.InputStream).ReadToEnd();
I believe what is happening is that "ReadToEnd()" is blocking my worker thread and when the TCP layer is lost the thread is stuck there trying to read indefinitely. How can I prevent this from happening?
I am currently coding in .NET 2.0 but I can use a newer framework if this is required.
Upvotes: 1
Views: 429
Reputation: 32818
HttpRequest.InputStream will synchronously read the entire request, then it returns the Stream as one huge chunk. You'll want something like this instead (requires .NET 4.5):
string body = await new StreamReader(request.GetBufferlessInputStream()).ReadToEndAsync();
GetBufferlessInputStream() won't read the entire request eagerly; it returns a Stream that reads the request on-demand. Then ReadToEndAsync() will asynchronously read from this Stream without tying up a worker thread.
To create a .NET 4.5-style async handler, subclass the HttpTaskAsyncHandler class. See this blog post for more information on async / await in .NET 4.5. You must also target .NET 4.5 in Web.config to get this functionality.
Upvotes: 2