C# 如何取消等待的任务?

C# 如何取消等待的任务?,c#,c#-4.0,task-parallel-library,C#,C# 4.0,Task Parallel Library,我正在尝试使用CancellationTokenSource取消等待网络IO的任务,但我必须等待TcpClient连接: try { while (true) { token.Token.ThrowIfCancellationRequested(); Thread.Sleep(int.MaxValue); //simulating a TcpListener waiting for request } } 有什么想法吗 其次,可以在单独的

我正在尝试使用CancellationTokenSource取消等待网络IO的任务,但我必须等待TcpClient连接:

try
{
    while (true)
    {
        token.Token.ThrowIfCancellationRequested();
        Thread.Sleep(int.MaxValue); //simulating a TcpListener waiting for request
    }
}
有什么想法吗


其次,可以在单独的任务中启动每个客户端吗?

启动任务时,可以使用的重载传递取消令牌,任务将检查取消情况

或者,您可以使用并继续做其他工作。AcceptSync将调用通过您定义的SocketAsyncEventArgs参数附加的OnCompleted方法

internal class Program
{
    private static EventWaitHandle _signalFromClient;
    private static readonly string NameThatClientKnows = Guid.NewGuid().ToString();
    private static readonly CancellationTokenSource CancellationTokenSource = new CancellationTokenSource();

    private const int PingSendTimeout = 30000;
    private static Socket _connectedClientSocket;
    private static Socket _tcpServer;

    private static void Main(string[] args)
    {
        _signalFromClient = new EventWaitHandle(false, EventResetMode.AutoReset, NameThatClientKnows);

        _tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        _tcpServer.Bind(new IPEndPoint(IPAddress.Loopback, 0));
        _tcpServer.Listen(1);

        var asyncOpInfo = new SocketAsyncEventArgs();
        asyncOpInfo.Completed += CompletedConnectRequest;
        _tcpServer.AcceptAsync(asyncOpInfo);

        Console.WriteLine("Console stays open, connecting client will say something.");
        Console.ReadLine();
    }

    private static void CompletedConnectRequest(object sender, SocketAsyncEventArgs e)
    {
        Console.WriteLine("Client connected");

        _connectedClientSocket = e.AcceptSocket;

        Task.Factory.StartNew(SendSimpleMessage, CancellationTokenSource.Token);
    }

    private static void SendSimpleMessage()
    {
        while (!CancellationTokenSource.Token.IsCancellationRequested && _connectedClientSocket.Connected)
        {
            try
            {
                _connectedClientSocket.Send(Encoding.UTF8.GetBytes("PING"));
                _signalFromClient.WaitOne(PingSendTimeout);
            }
            catch (SocketException) { Dispose(); }
        }
    }

    private static void Dispose()
    {
        CancellationTokenSource.Cancel();

        _connectedClientSocket.Close();
        _tcpServer.Close();
    }
}
当然,使用缓冲区和其他必要的项/行为设置SocketAsyncEventArgs。
在Dispose()中,我取消任务并捕获调用Socket.Close在客户端和服务器øØ上可能引发的任何SocketException。

我使用了CancellationToken句柄,而不是创建新的句柄,这使代码更简单

var task = Listener.AcceptTcpClientAsync();
task.Wait(MainToken.Token);
MainToken.Token.ThrowIfCancellationRequested();

TCP类应该有一个方法,该方法接受某种类型的取消或超时,以便您可以在循环中的每个超时后检查CancellationToken。AFAIK only.net 4.5有这样的选项。相关:u应该将其作为答案发布!