taskFactory.startnew()使用的“ concellationToken”是什么?
-
02-10-2019 - |
题
http://msdn.microsoft.com/en-us/library/dd988458.aspx
UPD:
因此,让我们讨论这篇文章: 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
, ,该任务将立即取消,而无需分配工作线程。
其他提示
取消任务仍然是合作的。您不希望在一些关键操作的中间杀死线程。您需要检查它。
取消tokens比更简单的构造更好 ManualResetEvent
例如,为了对操作的信号关闭,因为您可以级联或组合它们,例如,您可以将一个用于整体应用程序关闭的操作,并且可以将其与一个用于取消特定任务的合并。任务只需要看一个 CancellationToken
但是您可以从任何一个 CancellationTokenSource
.
不隶属于 StackOverflow