Repository navigation
Description
Every TCP server accept loop works like this:
(1) Create and start the listener
(2) Loop, accepting TCP connections and dispatching them, typically by spawning a thread pool work item
(3) Close the listener to stop accepting new connections (typically done from a separate thread, since the thread running the accept loop is busy waiting for connections to arrive)
Unfortunately, the behavior when you close the listener is today really ugly. It varies based on whether you do a sync or async accept, and whether you use TcpListener or Socket directly. Additionally, given the way accept loops are typically implemented, there is a race that results in a different exception if the close happens while an accept is pending vs happening after one accept completes but we haven't looped around to issue the next accept yet.
If you happen to stop the listener while the accept is pending, you will get a SocketException. For sync accept, you'll get SocketError=Interrupted. For async accept, you'll get SocketError=OperationAborted. (This is on Windows, but I believe the Linux behavior was implemented to match Windows.) I believe this is due to differences in sync/async handling in the underlying WinSock APIs, but this doesn't really help our users.
Also note that it's not correct to assume that any SocketException from accept is because the listener was closed -- other error conditions may cause different SocketExceptions. Instead, you have to explicitly check for the correct SocketError as listed above, depending on whether you do a sync or async accept.
If you lose the race and stop the listener while an accept is not pending, you will get ObjectDisposedException for Socket and InvalidOperationException for TcpListener (with the unhelpful message "You must call the Start() method before calling this method."), for both sync and async accept. Since your dispatch logic is usually very short, you'll only rarely lose the race and see these exceptions, which may manifest to users as a rare and hard to diagnose exception.
Closing the listener is a standard thing to do and shouldn't result in an exception from accept -- and especially shouldn't result in four different exceptions you need to check for.
Ideally, Accept would have a way to return without exception but indicate that the listener was closed. Perhaps something like:
public class Socket
{
public Socket? TryAccept();
}where returning null indicates that the listener was closed. Similarly for async and TcpListener methods.
Alternatively, we could change the behavior of the existing accept methods to at least be consistent in the exceptions they throw when the listener is closed, and not be subject to the race described above. Throwing ObjectDisposedException in all cases seems reasonable. Note however that TcpListener doesn't implement IDisposable, so it's a bit weird to throw ObjectDisposedException there -- an alternative would be to throw InvalidOperationException for TcpListener, since that matches the behavior today when you lose the race. In theory, well-written apps should be handling these exceptions (ODE for Socket, IOE for TcpListener) today anyway, but in practice it seems likely that some are not, so changing the exception behavior here may break some apps -- though also lead to fixing the apps to work properly in all cases.
Related: #63114
Activity
[-]Add an API or option to not throw from Accept when the listener is closed[/-][+]Improve behavior of Accept when the listener is closed[/+]scalablecory commentedon Dec 24, 2021
Instead of a boolean, consider returning a
SocketError. While this does add an extra step for the caller of checking against a specific error code, it would be more generalized and in line with our other overloads e.g.int Socket.Receive (Span<byte>, SocketFlags, out System.Net.Sockets.SocketError)and howSocketAsyncEventArgsworks.antonfirsov commentedon Jan 4, 2022
Harmonizing existing API-s seems to be way harder and more risky (in terms of breaking changes) than adding new API-s so I vote for the latter.
A potential API proposal (that also deals with the concerns from #63115 (comment)) may look like this:
There are several open questions though:
Try*. Ideally it would be much better if we could name them without the prefix, but that is conflicting with existing overloads.TcpClientAPI-s? Depends on the verdict on [API Proposal]: Simple, modern TCP APIs #63162 I guess.karelz commentedon Jan 11, 2022
Triage: async may not be trivial.
Overall we like the idea, it needs more details to be finalized. ASP.NET asked for similar thing as part of Connection Abstraction. cc @Tratcher
Not critical -> Future.
dotnet-policy-service commentedon Oct 19, 2026
Due to lack of recent activity, this issue has been marked as a candidate for backlog cleanup. It will be closed if no further activity occurs within 14 more days. Any new comment (by anyone, not necessarily the author) will undo this process.
This process is part of our issue cleanup automation.
dotnet-policy-service commentedon Oct 19, 2026
Due to lack of recent activity, this issue has been marked as a candidate for backlog cleanup. It will be closed if no further activity occurs within 14 more days. Any new comment (by anyone, not necessarily the author) will undo this process.
This process is part of our issue cleanup automation.
dotnet-policy-service commentedon Nov 16, 2026
This issue will now be closed since it had been marked
no-recent-activitybut received no further activity in the past 14 days. It is still possible to reopen or comment on the issue, but please note that the issue will be locked if it remains inactive for another 30 days.