As everyone may already know, the simplest way to accept incoming TCP connections in C# is by looping over TcpListener.AcceptTcpClient(). Additionally this way will block co
For completeness, async counterpart of the answer above:
async Task AcceptAsync(TcpListener listener, CancellationToken ct)
{
using (ct.Register(listener.Stop))
{
try
{
return await listener.AcceptTcpClientAsync();
}
catch (SocketException e)
{
if (e.SocketErrorCode == SocketError.Interrupted)
throw new OperationCanceledException();
throw;
}
}
}
Update: As @Mitch suggests in comments (and as this discussion confirms), awaiting AcceptTcpClientAsync may throw ObjectDisposedException after Stop (which we are calling anyway), so it makes sense to catch ObjectDisposedException too:
async Task AcceptAsync(TcpListener listener, CancellationToken ct)
{
using (ct.Register(listener.Stop))
{
try
{
return await listener.AcceptTcpClientAsync();
}
catch (SocketException e) when (e.SocketErrorCode == SocketError.Interrupted)
{
throw new OperationCanceledException();
}
catch (ObjectDisposedException) when (ct.IsCancellationRequested)
{
throw new OperationCanceledException();
}
}
}