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

前端 未结 7 739
醉话见心
醉话见心 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:46

    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(); }
    }
    
    • I register a callback to call Stop() on the TcpListener instance when the CancellationToken gets canceled.
    • AcceptSocketAsync typically immediately throws an ObjectDisposedException then.
    • I catch any 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!

提交回复
热议问题