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

标签 c# sockets .net-4.5 c#-5.0

我不知道如何在异步方法等待传入连接时正确关闭 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/

相关文章:

c# - 按实体查询(示例)

javascript - HTML5 的平台独立容器,可以从套接字发送/接收数据

c# - 样式下拉列表选择项

c# - 为 Log4Net 中的特定异常设置日志记录级别(对于 Episerver)

c# - 如何在不跳过的情况下精确跟踪鼠标坐标

sockets - Debian - 每个用户的默认 IP?

visual-studio-2015 - 如何在 VS 2015/.NET 4.6 中添加引用?

c# - SomeButNotAll() 是否有优雅的 LINQ 解决方案?

c# - 如何在每个层次结构 (TPH) 映射的表中共享公共(public)列名

android - 如何将套接字/文件描述符传递给Android中的其他应用程序