我不知道如何在异步方法等待传入连接的同时正确关闭TcpListener。
我在SO上找到了此代码,这里是代码:

public class Server
{
    private TcpListener _Server;
    private bool _Active;

    public Server()
    {
        _Server = new TcpListener(IPAddress.Any, 5555);
    }

    public async void StartListening()
    {
        _Active = true;
        _Server.Start();
        await AcceptConnections();
    }

    public void StopListening()
    {
        _Active = false;
        _Server.Stop();
    }

    private async Task AcceptConnections()
    {
        while (_Active)
        {
            var client = await _Server.AcceptTcpClientAsync();
            DoStuffWithClient(client);
        }
    }

    private void DoStuffWithClient(TcpClient client)
    {
        // ...
    }

}

和主要:
    static void Main(string[] args)
    {
        var server = new Server();
        server.StartListening();

        Thread.Sleep(5000);

        server.StopListening();
        Console.Read();
    }

在此行抛出异常
        await AcceptConnections();

当我调用Server.StopListening()时,该对象被删除。

所以我的问题是,如何取消AcceptTcpClientAsync()以正确关闭TcpListener。

最佳答案

由于这里没有合适的工作示例,因此这里是一个示例:

假设您同时在cancellationTokentcpListener的范围内,那么您可以执行以下操作:

using (cancellationToken.Register(() => tcpListener.Stop()))
{
    try
    {
        var tcpClient = await tcpListener.AcceptTcpClientAsync();
        // … carry on …
    }
    catch (InvalidOperationException)
    {
        // Either tcpListener.Start wasn't called (a bug!)
        // or the CancellationToken was cancelled before
        // we started accepting (giving an InvalidOperationException),
        // or the CancellationToken was cancelled after
        // we started accepting (giving an ObjectDisposedException).
        //
        // In the latter two cases we should surface the cancellation
        // exception, or otherwise rethrow the original exception.
        cancellationToken.ThrowIfCancellationRequested();
        throw;
    }
}

关于c# - TcpListener : how to stop listening while awaiting AcceptTcpClientAsync()?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19220957/

10-12 22:32