gpt4 book ai didi

C#: CancellationToken 不取消阻塞方法

转载 作者:太空狗 更新时间:2023-10-29 18:28:52 24 4
gpt4 key购买 nike

.NET 4.5.1:看来,我无法使用 CancellationTokenSource 内置超时取消在任务中运行的阻塞方法。

class Program
{
static void Main(string[] args)
{
var cts = new System.Threading.CancellationTokenSource();

System.Console.CancelKeyPress += (s, e) =>
{
e.Cancel = true;
cts.Cancel();
};

MainAsync(args, cts.Token).Wait();
}

// MainAsync from http://stackoverflow.com/questions/9208921/async-on-main-method-of-console-app
static async Task MainAsync(string[] args, System.Threading.CancellationToken token)
{
Console.WriteLine("Starting MainAsync");
var cts = new System.Threading.CancellationTokenSource(3000);
var task = Task.Factory.StartNew(() =>
{
Console.WriteLine("Starting task...");
var t = new System.Net.Sockets.TcpClient();
var buffer = new byte[t.ReceiveBufferSize];
t.Connect(new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 1337));

Console.WriteLine("Recieving...");
t.Client.Receive(buffer);
Console.WriteLine("Finished Recieving...");

return true;
}, cts.Token);

var success = await task;

Console.WriteLine("Did the task complete succesfuly?", success);
}
}

上述简短、自包含、正确示例的输出(我希望它是正确的)是:

Starting MainAsync
Starting task...
Recieving...

为什么任务没有取消,没有抛出异常?

最佳答案

正如我在博客中所述,"You keep using that CancellationToken there. I do not think it means what you think it means."

特别是,传递给StartNewCancellationToken 只会取消委托(delegate)的开始。如果您希望委托(delegate)本身支持取消,则委托(delegate)本身必须观察 CancellationToken

关于C#: CancellationToken 不取消阻塞方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33855450/

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