有什么方法可以在 .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);
}