Skip to content

Closing the AsyncWaitHandle from the result of socket.BeginConnect crashes the application in .NET 6.0 #64400

Closed

Description

@MaxG117

Description

The simple code below works on all versions of .NET before 6.0, but crashes with "Unhandled exception. System.ObjectDisposedException: Safe handle has been closed." on net6.0:

using System;
using System.Net;
using System.Net.Sockets;

namespace Net60SafeHandleBug
{
    class Program
    {
        static void Main(string[] args)
        {
            int port = 1234;
            IPAddress.TryParse("127.0.0.1", out IPAddress ipAddress);
            Socket socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            IAsyncResult asyncResult = socket.BeginConnect(ipAddress, port, null, null);
            // do something, then suddenly quit...
            socket.Close();
            asyncResult.AsyncWaitHandle.Close(); // <-- ruh roh

            Console.WriteLine("Press any key to quit...");
            Console.ReadKey();
        }
    }
}

Reproduction Steps

Build the above code as a console app. It will crash when targeting net6.0, but work fine with any older version of .NET.

Expected behavior

The application should succeed. The documentation for IAsyncResult.AsyncWaitHandle does not mention that one must wait for the handle to be signaled or call the APM End* method before closing, but it does say that the handle should be closed when the application is done using it.

Actual behavior

The application crashes with the following:

System.ObjectDisposedException
  HResult=0x80131622
  Message=Safe handle has been closed.
Object name: 'SafeHandle'.
  Source=System.Private.CoreLib
  StackTrace:
   at System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success)
   at Interop.Kernel32.SetEvent(SafeWaitHandle handle)
   at System.Threading.EventWaitHandle.Set()
   at System.Threading.ManualResetEventSlim.Set(Boolean duringCancellation)
   at System.Threading.Tasks.Task.FinishStageTwo()
   at System.Threading.Tasks.Task.FinishSlow(Boolean userDelegateExecute)
   at System.Threading.Tasks.Task.TrySetException(Object exceptionObject)
   at System.Threading.Tasks.ValueTask.ValueTaskSourceAsTask.<>c.<.cctor>b__4_0(Object state)
   at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.InvokeContinuation(Action`1 continuation, Object state, Boolean forceAsync, Boolean requiresExecutionContextFlow)
   at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.OnCompleted(SocketAsyncEventArgs _)
   at System.Net.Sockets.SocketAsyncEventArgs.OnCompletedInternal()
   at System.Net.Sockets.SocketAsyncEventArgs.HandleCompletionPortCallbackError(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
   at System.Net.Sockets.SocketAsyncEventArgs.<>c.<.cctor>b__179_0(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
   at System.Threading.ThreadPoolBoundHandleOverlapped.CompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
   at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pNativeOverlapped)

Regression?

This is a regression in .NET 6.0, because it works in all the prior versions.

Known Workarounds

No response

Configuration

Tested on net461, netcoreapp2.0, net5.0, and net6.0 running on Windows 10 (x64). Did not test on other platforms.

Other information

No response

Activity

  1. ghost added
    untriaged
    on Jan 27, 2022
  2. changed the title [-]Closing the AsyncWaitHandle from socket.BeginConnect crashes the application in .NET 6.0[/-] [+]Closing the AsyncWaitHandle from the result of socket.BeginConnect crashes the application in .NET 6.0[/+] on Jan 27, 2022
  3. stephentoub commented on Jan 27, 2022

    @stephentoub
    Member

    The documentation for IAsyncResult.AsyncWaitHandle does not mention that one must wait for the handle to be signaled or call the APM End* method before closing

    It may not say so (though it does say "Once created, AsyncWaitHandle should be kept alive until the user calls the method that concludes the asynchronous operation. At that time the object behind AsyncWaitHandle can be discarded."), but that is the intention. Until the operation has quiesced, it's going to want to set that wait handle when it completes, and if you close it out from under it, there's inherently a race condition between you closing it and the implementation trying to use it.

  4. MaxG117 commented on Jan 27, 2022

    @MaxG117
    Author

    We believe that Socket.Close() is supposed to cancel or abort any outstanding APM operation: "The Close method closes the remote host connection and releases all managed and unmanaged resources associated with the Socket." We shouldn't have to wait for the outstanding socket operations to complete, and since there's no other way to cancel the BeginConnect, Socket.Close() is supposed to do that, and this is how it has worked since the early days of .NET Framework. After Socket.Close is called, there should be no operation attempting to set the wait handle, so we should be able to close the handle.

  5. MaxG117 commented on Feb 1, 2022

    @MaxG117
    Author

    @stephentoub:

    I ran some experiments. In .NET 5.0 and earlier, the wait handle is always signaled by the time socket.Close() returns. In .NET 6.0, socket.Close() returns much faster (~0.2ms vs 3ms) and the wait handle is not signaled until later.

    The paragraph you quoted is in the "Notes to Implementers" section. I.e., the implementers of IAsyncResult. I think you implied that it is my responsibility to wait for the wait handle, while the actual document states that it is the responsibility of the implementer of IAsyncResult, which in this case is Socket. Here's the entire paragraph (emphasis mine):

    The object that implements IAsyncResult does not need to create the WaitHandle until the AsyncWaitHandle property is read. It is the choice of the IAsyncResult implementer. However, if the implementer creates AsyncWaitHandle, it is the responsibility of the implementer to signal the WaitHandle that will terminate the wait at the appropriate time. For example, AsyncResult terminates the wait on behalf of the caller when an asynchronously invoked method returns. Once created, AsyncWaitHandle should be kept alive until the user calls the method that concludes the asynchronous operation. At that time the object behind AsyncWaitHandle can be discarded.

    Further, in the "Notes to Callers" it states:

    Note: When you use the BeginInvoke method of a delegate to call a method asynchronously and obtain a wait handle from the resulting IAsyncResult, we recommend that you close the wait handle as soon as you are finished using it, by calling the Close() method. If you simply release all references to the wait handle, system resources are freed when garbage collection reclaims the wait handle, but garbage collection works more efficiently when disposable objects are explicitly closed or disposed. For more information, see the AsyncWaitHandle property.

    The .NET Socket implementation is the implementer of the IAsyncResult interface. My application is the user of that implementation. I called the socket.Close() method to conclude the asynchronous operation, since there's no other method to conclude or cancel the socket.BeginConnect() operation. Therefore I should now be able to discard the object behind AsyncWaitHandle by calling Close(), as described in the documentation.

  6. stephentoub commented on Feb 1, 2022

    @stephentoub
    Member

    while the actual document states that it is the responsibility of the implementer of IAsyncResult

    That's intended to mean the disposal should be done as part of the EndXx call, not that the implementor waits on their own event. In fact most implementations don't even create the event until someone asks for it.

    Further, in the "Notes to Callers" it states:

    That's specifically about Delegate.BeginInvoke. It's not relevant. It's not even functional anymore.

  7. self-assigned this
    on Feb 1, 2022
  8. added this to the 7.0.0 milestone on Feb 1, 2022
  9. ghost added
    in-pr
    on Feb 1, 2022
  10. MaxG117 commented on Feb 1, 2022

    @MaxG117
    Author

    @stephentoub I see you targeted 7.0 -- is there any chance this can be fixed in 6.0? 6.0 is the LTS that'll be around for many years. Thank you!

  11. GSPP commented on Feb 2, 2022

    @GSPP

    Who is actually responsible for closing a wait handle that an IAsyncResult produced? I always assumed that's the responsibility of the implementer (typically done in the end method). A user should never close that handle.

    This piece of documentation seems to contradict that (so I think it's wrong):

    we recommend that you close the wait handle as soon as you are finished using it, by calling the Close() method

    If that documentation is wrong, @MaxG117 could simply stop closing the handle.

    @MaxG117 If you are looking for an immediate workaround, you can create your own handle or use the Task based API and block on that task (I'd prefer to do that over the APM pattern in any case).

  12. stephentoub commented on Feb 2, 2022

    @stephentoub
    Member

    see you targeted 7.0 -- is there any chance this can be fixed in 6.0?

    Any chance, sure :-) but at this point I expect we'd want to see more devs reporting an issue before we took a servicing fix for it. This Task code has been like this for over a decade, and while Task wasn't used as the IAsyncResult for BeginConnect until relatively recently, it has been used without any such reported issues as the IAsyncResult for most APM implementations in NET Core for years, including for most other Socket APM implementations.

    As noted, it's really not recommended to Dispose the wait handle yourself, in particular not before the operation completes (for better or worse the docs show closing it after completion, which is more reasonable, as at that point you can be more sure no one else is still using it, and if EndXx did Dispose it, your disposal will just nop). It's typically owned by the APM implementation, which may dispose it as part of EndXx, and it can otherwise be left for finalization (while we generally want to avoid finalization for perf reasons, if you're using the APM pattern and synchronously blocking on the wait handle, perf is not a primary concern). On top of that, the APM pattern is largely defunct and definitely not recommended for new code; existing code should be migrating off of it if at all possible. And even if code continues using it, the sync blocking on a wait handle for the IAsyncResult is also not the preferred approach, as such blocking leads to poorer scalability and greater risk of starvation and deadlocks. Most of our custom APM implementations have been ripped out and replaced by just layering on top of the corresponding Task-based APIs, which are easier to consume and better performing.

    it doesn't help that the APM pattern is really hard to both implement and consume, which also means there have historically been many inconsistencies in implementations, many subtle bugs in code consuming it, and less than stellar docs around it.

  13. GSPP commented on Feb 2, 2022

    @GSPP

    It's a pity that Task was not in .NET 1.0. IAsyncResult is actually super close to Task: All that's missing is ContinueWith. Everything else can be derived from that.

  14. 1 remaining item

  15. MaxG117 commented on Feb 2, 2022

    @MaxG117
    Author

    @GSPP the Task-based Socket APIs were just released a few months ago in .NET 6.0. We've been using the APM pattern for over a decade and our product still supports .NET Framework 4.6.x. We also provide a .NET Standard 2.0 library, but because of this bug in the Socket reimplementation of APM around a Task, our .NET Standard 2.0 library is incompatible with the NET 6.0 runtime.

    Also I don't need to create another handle or Task -- the simplest workaround is to wait for the AsyncWaitHandle to be signaled before closing it, which happens shortly after socket.Close() returns. But our resident .NET expert and I both believe that this is a bug in Socket that should be fixed in .NET 6.0, and we've not been convinced by the comments here that we're doing something wrong. Socket.Close() should signal the handle before returning.

  16. antonfirsov commented on Feb 2, 2022

    @antonfirsov
    Contributor

    @MaxG117 if performance matters, I would recommend to move to EAP / SocketAsyncEventArgs, which is fully functional on .NET Framework. APM is really bad at perf, and in general a legacy API today.

  17. MaxG117 commented on Feb 2, 2022

    @MaxG117
    Author

    @antonfirsov thanks, I'll take a look. Our library is a network client, not a server, so I'm not sure how much we could gain from switching to EAP. By "performance" I was referring to a specific operation -- the establishing of a single socket connection. A failed connection takes many seconds to fail due to TCP (and the default TCP settings on various OSes). We avoid these "fail" delays by trying to open multiple connections (to different endpoints) asynchronously, expecting at least one to succeed much faster than the TCP fail delay.

  18. antonfirsov commented on Feb 2, 2022

    @antonfirsov
    Contributor

    EAP model is also superior from compatibility perspective. You may also consider not touching the WaitHandle at all, and get notified about completion in other ways, for example in an AsyncCallback. In that case it won't be lazily created -- no need to dispose. As mentioned in #64400 (comment), if blocking on the WaitHandle was fine in your library, you probably don't have that critical scalability needs, so leaving the handle to the finalizer might be also OK.

  19. MaxG117 commented on Feb 2, 2022

    @MaxG117
    Author

    Just because I'm using WaitHandle.WaitAny(...) doesn't mean I don't have critical scalability needs :)

    I do not need to be notified of completion by the failing socket.BeginConnect(...) operations -- I need to cancel them. I've already been notified of completion of at least one operation by WaitAny so I know which socket has connected. I don't need the rest of them, so I'm cleaning up by canceling the still-in-progress-and-soon-to-fail asynchronous operations with socket.Close() and asyncResult.AsyncWaitHandle.Close(), because:

    we recommend that you close the wait handle as soon as you are finished using it, by calling the Close() method

    Based on the evidence (as opposed to source code, which I haven't dug into), in previous releases socket.Close() has always signaled the wait handle before returning to the caller. This changed in 6.0 because of a big redesign of Socket. It is the responsibility of socket.Close() to abort any and all outstanding asynchronous socket operations, and it must do so before returning, because socket.Close() is a synchronous operation. It behaves like one might expect socket.CloseAsync() to behave. This is wrong.

  20. stephentoub commented on Feb 3, 2022

    @stephentoub
    Member

    socket.Close() has always signaled the wait handle before returning to the caller

    I just ran this on .NET Framework 4.8, and pretty much every iteration shows that the WaitHandle has not been signaled. You see otherwise?

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    
    internal class Program
    {
        static void Main()
        {
            for (long i = 0; ; i++)
            {
                var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IAsyncResult iar = socket.BeginConnect(new DnsEndPoint("bing.com", 80), _ => { }, null);
                WaitHandle wh = iar.AsyncWaitHandle;
                socket.Close();
    
                if (wh.WaitOne(0))
                {
                    Console.WriteLine($"{i}: Set");
                }
                else
                {
                    Console.WriteLine($"{i}: Not set");
                }
            }
        }
    }

    produces

    0: Not set
    1: Not set
    2: Not set
    3: Not set
    4: Not set
    5: Not set
    6: Not set
    7: Not set
    8: Not set
    9: Not set
    10: Not set
    11: Not set
    12: Not set
    13: Not set
    14: Not set
    15: Not set
    16: Not set
    17: Not set
    18: Not set
    19: Not set
    20: Not set
    21: Not set
    22: Not set
    23: Not set
    24: Not set
    25: Not set
    ...
    
  21. MaxG117 commented on Feb 3, 2022

    @MaxG117
    Author

    Gotta be careful, last I checked the code path was different for DnsEndPoint.
    I tried the code in the description above (against an unresponsive IPAddress & port) with net461 and netstandard2.0. It's possible that I was mistaken or misinterpreted the results about the handle being signaled by socket.Close, but I do know that closing the handle does not cause any exceptions. I'd try it again for my own sanity but I'm away from my machine til next week.

  22. GSPP commented on Feb 3, 2022

    @GSPP

    Can you first close the socket, then call End to release resources? It seems that this should be the pattern to use, since calling End is contractually required. Close should quickly finish the APM operation, so that End should complete very quickly. The wait handle would then not need to be disposed.

  23. antonfirsov commented on Feb 3, 2022

    @antonfirsov
    Contributor

    EndConnect after close will throw ObjectDisposedException. We are about to change in future versions (#61411 (comment)).

  24. stephentoub commented on Feb 3, 2022

    @stephentoub
    Member

    Gotta be careful, last I checked the code path was different for DnsEndPoint.

    It doesn't affect the fact that there's no guarantee (and never has been) about the wait handle being set. This example uses IPEndPoint:

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    
    internal class Program
    {
        static void Main()
        {
            IPAddress[] addresses = Dns.GetHostAddresses("bing.com");
    
            for (long i = 0; ; i++)
            {
                var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IAsyncResult iar = socket.BeginConnect(new IPEndPoint(addresses[0], 80), _ => { }, null);
                WaitHandle wh = iar.AsyncWaitHandle;
                socket.Close();
    
                if (wh.WaitOne(0))
                {
                    Console.WriteLine($"{i}: Set");
                }
                else
                {
                    Console.WriteLine($"{i}: Not set");
                }
            }
        }
    }

    just produced for me on .NET Framework 4.8:

    0: Not set
    1: Not set
    2: Not set
    3: Not set
    4: Not set
    5: Not set
    6: Not set
    7: Not set
    8: Set
    9: Not set
    10: Not set
    11: Not set
    12: Not set
    13: Not set
    14: Not set
    15: Not set
    16: Not set
    17: Not set
    18: Not set
    19: Not set
    20: Not set
    21: Not set
    22: Not set
    23: Not set
    24: Not set
    25: Not set
    26: Not set
    27: Not set
    28: Not set
    29: Not set
    30: Not set
    31: Not set
    32: Not set
    33: Not set
    34: Not set
    35: Not set
    36: Not set
    37: Not set
    38: Not set
    39: Not set
    40: Not set
    ...
    
  25. geoffkizer commented on Feb 3, 2022

    @geoffkizer
    Contributor

    the Task-based Socket APIs were just released a few months ago in .NET 6.0.

    Task-based Socket APIs have been in .NET Core forever.

  26. ghost removed
    in-pr
    on Feb 4, 2022
  27. ghost locked as resolved and limited conversation to collaborators on Mar 6, 2022
  28. removed
    untriaged
    on Oct 20, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions