在CancellationToken上停止AcceptTcpClient

时间:2013-04-05 22:25:00

标签: multithreading sockets .net-4.0 network-programming tcplistener

有没有办法在.net4中检查CancellationToken同时接受客户端。

    while (!token.IsCancellationRequested)
    {
        //change this somehow to use check cancellation but keep this blocking
        TcpClient client = _tcpListener.AcceptTcpClient();
        var client= new myclient(client);
        _clients.Add(telemetryClient);
    }

到目前为止我能做的最好,还不够干净:

        while (!token.IsCancellationRequested)
        {
            var acceptTask = Task<TcpClient>.Factory.FromAsync(_tcpListener.BeginAcceptTcpClient, _tcpListener.EndAcceptTcpClient, null);
            var tokenTask = Task.Factory.StartNew(() =>
                {
                    while (!token.IsCancellationRequested)
                    {
                        Thread.Sleep(1000);
                    }
                    return;
                }, token);
            Task.WaitAny(new Task[] { acceptTask ,tokenTask}, token);

            if (token.IsCancellationRequested)
                break;

            TcpClient client = acceptTask.Result;//_tcpListener.AcceptTcpClient();
            var client = new myclient(client);
            _clients.Add(telemetryClient);
        }

1 个答案:

答案 0 :(得分:0)

仅仅这样做是不够的 Task.WaitAny(acceptTask,token)?

即我没有看到为什么需要tokenTask。

此外,如果发生取消,然后acceptTask遇到异常,您可能会发现出现“未观察到的异常”情况。考虑使用TaskScheduler.UnobservedTaskException来捕获(并可能忽略)那些。

-Mike