I don\'t know how to properly close a TcpListener while an async method await for incoming connections. I found this code on SO, here the code :
public class
I used the following solution when continually listening for new connecting clients:
public async Task ListenAsync(IPEndPoint endPoint, CancellationToken cancellationToken)
{
TcpListener listener = new TcpListener(endPoint);
listener.Start();
// Stop() typically makes AcceptSocketAsync() throw an ObjectDisposedException.
cancellationToken.Register(() => listener.Stop());
// Continually listen for new clients connecting.
try
{
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
Socket clientSocket = await listener.AcceptSocketAsync();
}
}
catch (OperationCanceledException) { throw; }
catch (Exception) { cancellationToken.ThrowIfCancellationRequested(); }
}
Stop() on the TcpListener instance when the CancellationToken gets canceled.AcceptSocketAsync typically immediately throws an ObjectDisposedException then.Exception other than OperationCanceledException though to throw a "sane" OperationCanceledException to the outer caller.I'm pretty new to async programming, so excuse me if there's an issue with this approach - I'd be happy to see it pointed out to learn from it!