gpt4 book ai didi

c# - TaskFactory.StartNew() 中的 "cancellationToken"有什么用?

转载 作者:可可西里 更新时间:2023-11-01 03:13:27 33 4
gpt4 key购买 nike

http://msdn.microsoft.com/en-us/library/dd988458.aspx

更新:

所以,让我们讨论这篇文章:http://msdn.microsoft.com/en-us/library/dd997396.aspx

我稍微修改了一下代码:

    static void Main()
{

var tokenSource2 = new CancellationTokenSource();
CancellationToken ct = tokenSource2.Token;

var task = Task.Factory.StartNew(() =>
{

// Were we already canceled?
ct.ThrowIfCancellationRequested();

bool moreToDo = true;
Thread.Sleep(5000);
while (moreToDo)
{

// Poll on this property if you have to do
// other cleanup before throwing.
if (ct.IsCancellationRequested)
{
Console.WriteLine("exit");
// Clean up here, then...
ct.ThrowIfCancellationRequested();
}

}
}, tokenSource2.Token); // this parameter useless

Console.WriteLine("sleep");
Thread.Sleep(2000);
Console.WriteLine("cancel");

tokenSource2.Cancel();

// Just continue on this thread, or Wait/WaitAll with try-catch:
try
{
task.Wait();
}
catch (AggregateException e)
{
foreach (var v in e.InnerExceptions)
{
Console.WriteLine(e.Message + " " + v.Message);
}
}

Console.ReadKey();
}

UPD:好吧,这只会改变 task.IsCanceled,恕我直言,这是无用的,因为我仍然应该手动实现所有内容。

最佳答案

由于评论,我发布了另一个答案。

考虑以下代码:

var tokenSource = new CancellationTokenSource();
CancellationToken ct = tokenSource.Token;

tokenSource.Cancel();

var task = Task.Factory.StartNew(() =>
{
// Were we already canceled?
ct.ThrowIfCancellationRequested();
// do some processing
});

即使调用 tokenSource.Cancel() 是在任务实际开始之前发出的,您仍然会从线程池中分配一个工作线程,因此您会浪费一些系统资源。

但是当您在 Task.Factory.StartNew 中指定 token 参数时,任务将立即取消,而不分配工作线程。

关于c# - TaskFactory.StartNew() 中的 "cancellationToken"有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3689765/

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