ObjectDisposedException when calling Abort in an HttpWebRequest used asynchronously

As you can see from the header, I seem to get it ObjectDisposedExceptionwhen I call "Abort"on HttpWebRequest, used asynchronously (i.e. BeginGetResponse), and I cannot, in my opinion, figure out how to prevent this. I searched all day 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's what I do: 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 a timeout callback is performed, I get the above ObjectDisposedException( "Timed out!"written to the console first). I do not get this exception unless I call Aborton HttpWebRequest.

- , ? .NET 3.5. .

/ :

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
+3

Source: https://habr.com/ru/post/1780136/


All Articles