gpt4 book ai didi

c# - 如何取消等待中的任务?

转载 作者:行者123 更新时间:2023-11-30 22:23:08 26 4
gpt4 key购买 nike

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

try
{
while (true)
{
token.Token.ThrowIfCancellationRequested();
Thread.Sleep(int.MaxValue); //simulating a TcpListener waiting for request
}
}

有什么想法吗?

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

最佳答案

当您开始任务时,您可以使用 StartNew 的重载传递取消 token ,您的任务将检查取消。

或者你可以使用 AcceptAsync并继续做其他工作。 AcceptAsync 将调用通过您定义的 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 引发的任何 SocketExceptions。

关于c# - 如何取消等待中的任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13520632/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com