Repository navigation
Description
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
[-]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[/+]stephentoub commentedon Jan 27, 2022
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.
MaxG117 commentedon Jan 27, 2022
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.
MaxG117 commentedon Feb 1, 2022
@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):
Further, in the "Notes to Callers" it states:
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.
stephentoub commentedon Feb 1, 2022
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.
That's specifically about Delegate.BeginInvoke. It's not relevant. It's not even functional anymore.
MaxG117 commentedon Feb 1, 2022
@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!
GSPP commentedon Feb 2, 2022
Who is actually responsible for closing a wait handle that an
IAsyncResultproduced? 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):
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
Taskbased API and block on that task (I'd prefer to do that over the APM pattern in any case).stephentoub commentedon Feb 2, 2022
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.
GSPP commentedon Feb 2, 2022
It's a pity that
Taskwas not in .NET 1.0.IAsyncResultis actually super close toTask: All that's missing isContinueWith. Everything else can be derived from that.1 remaining item
MaxG117 commentedon Feb 2, 2022
@GSPP the Task-based
SocketAPIs 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 theSocketreimplementation 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
Socketthat 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.antonfirsov commentedon Feb 2, 2022
@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.MaxG117 commentedon Feb 2, 2022
@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.
antonfirsov commentedon Feb 2, 2022
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.MaxG117 commentedon Feb 2, 2022
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 byWaitAnyso 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 withsocket.Close()andasyncResult.AsyncWaitHandle.Close(), because: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 ofSocket. It is the responsibility ofsocket.Close()to abort any and all outstanding asynchronous socket operations, and it must do so before returning, becausesocket.Close()is a synchronous operation. It behaves like one might expectsocket.CloseAsync()to behave. This is wrong.stephentoub commentedon Feb 3, 2022
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?
produces
MaxG117 commentedon Feb 3, 2022
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.
GSPP commentedon Feb 3, 2022
Can you first close the socket, then call
Endto 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.antonfirsov commentedon Feb 3, 2022
EndConnectafter close will throwObjectDisposedException. We are about to change in future versions (#61411 (comment)).stephentoub commentedon Feb 3, 2022
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:
just produced for me on .NET Framework 4.8:
geoffkizer commentedon Feb 3, 2022
Task-based Socket APIs have been in .NET Core forever.