TcpListener: how to stop listening while awaiting AcceptTcpClientAsync()?

前端 未结 7 738
醉话见心
醉话见心 2020-12-29 07:14

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         


        
相关标签:
7条回答
  • 2020-12-29 07:47

    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());
    
    0 讨论(0)
提交回复
热议问题