3

As the title indicates, I seem to be getting an ObjectDisposedException when calling "Abort" on an HttpWebRequest used asynchronously (i.e. BeginGetResponse) and can't, for the life of me, figure out how to prevent it. I have spent all day searching for a solution so any help would be appreciated. Here is a simple example illustrating the problem:

// helper class that gets passed through as the state
class RequestState
{
    public HttpWebRequest Request { get; set; }
    public bool TimedOut { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var rs = new RequestState
        {
            Request = (HttpWebRequest)WebRequest.Create("http://google.com")
        };

        var result = rs.Request.BeginGetResponse(
            asyncResult =>
            {
                if (asyncResult.IsCompleted)
                {
                    var reqState = asyncResult.AsyncState as RequestState;

                    if (reqState != null && !reqState.TimedOut)
                    {
                        using (var response = reqState.Request.EndGetResponse(asyncResult) as HttpWebResponse)
                        {
                            using (var streamReader = new StreamReader(response.GetResponseStream()))
                            {
                                Console.WriteLine(streamReader.ReadToEnd());
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("Timed out!");
                    }
                }
            },
            rs);

        ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle,
            (state, timeout) =>
            {
                if (timeout)
                {
                    var temprs = state as RequestState;
                    if (temprs != null)
                    {
                        // set TimedOut flag
                        temprs.TimedOut = true;
                        // this will cause the BeginGetResponse callback above to be called
                        temprs.Request.Abort();
                    }
                    // after this method leaves scope the ObjectDisposedException occurs!
                }
            },
            // time out of 7 seconds
            rs, 7000, true);

        Console.ReadLine();


    }
}

Here is what I am doing: If I run this normally, the response is written to the console just fine. However, if I use Fiddler to simulate a slow internet connection (or basically no connection) and the timeout callback executes, I get the aforementioned ObjectDisposedException ("Timed out!" is written to the console first though). I do not get this exception if I do not call Abort on the HttpWebRequest.

Can anyone tell me what I am doing wrong? I am targeting the .NET 3.5 framework. Thank you in advance for any enlightenment.

Here is the exception info/call stack:

System.ObjectDisposedException occurred
    Message=Cannot access a disposed object.
Object name: 'System.Net.Sockets.NetworkStream'.
    Source=System
    ObjectName=System.Net.Sockets.NetworkStream
    StackTrace:
        at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
    InnerException: 

System.Net.Sockets.NetworkStream.EndRead(System.IAsyncResult asyncResult) + 0x1b7 bytes 
System.Net.PooledStream.EndRead(System.IAsyncResult asyncResult) + 0x10 bytes   
System.Net.Connection.ReadCallback(System.IAsyncResult asyncResult) + 0x33 bytes    
System.Net.Connection.ReadCallbackWrapper(System.IAsyncResult asyncResult) + 0x46 bytes 
System.Net.LazyAsyncResult.Complete(System.IntPtr userToken) + 0x69 bytes   
System.Net.ContextAwareResult.Complete(System.IntPtr userToken) + 0xab bytes    
System.Net.LazyAsyncResult.ProtectedInvokeCallback(object result, System.IntPtr userToken) + 0xb0 bytes 
System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(uint errorCode, uint numBytes, System.Threading.NativeOverlapped* nativeOverlapped) + 0x94 bytes    
System.Threading._IOCompletionCallback.PerformIOCompletionCallback(uint errorCode, uint numBytes, System.Threading.NativeOverlapped* pOVERLAP) + 0x54 bytes
skwear
  • 563
  • 1
  • 5
  • 24
dreyln
  • 860
  • 1
  • 9
  • 18
  • Since you're using closures anyway, there is no point in `AsyncState`. – SLaks Dec 14 '10 at 02:03
  • Yes, that is true. When I initially coded this, I had the callbacks as named methods, but I didn't bother doing that when I put together the short example code to illustrate the problem. I'll post the stack trace tomorrow when I get back to work. Thanks – dreyln Dec 16 '10 at 06:53
  • This problem appears when I use System.Net.Http.HttpClient, which uses HttpWebRequest. It may be causing some bad unreliability for when the url is bad. I posted about it: http://stackoverflow.com/questions/19868292/httpclient-async-requests-not-completing-for-large-batch-sent-out-in-a-loop – Elliot Nov 14 '13 at 21:46
  • This is still happening, I have a partial work around http://stackoverflow.com/questions/23532249/net-4-5-httpclient-objectdisposedexception-on-timeout – Matt May 08 '14 at 06:15

0 Answers0