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
Define this extension method:
public static class Extensions
{
public static async Task<TcpClient> AcceptTcpClientAsync(this TcpListener listener, CancellationToken token)
{
try
{
return await listener.AcceptTcpClientAsync();
}
catch (Exception ex) when (token.IsCancellationRequested)
{
throw new OperationCanceledException("Cancellation was requested while awaiting TCP client connection.", ex);
}
}
}
Before using the extension method to accept client connections, do this:
token.Register(() => listener.Stop());