What is “cancellationToken” in the TaskFactory.StartNew() used for?

穿精又带淫゛_ 提交于 2019-11-29 03:28:01

Due to comments, I'm posting another answer.

Consider the following code:

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

tokenSource.Cancel(); 

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

Even if the call tokenSource.Cancel() is issued before the task was actually started, you'll still allocate a worker thread from thread pool, so you'll waste some system resources.

But when you specify token argument in Task.Factory.StartNew, the task will be cancelled immediately, without allocating a worker thread.

Cancellation with Tasks is still cooperative. You wouldn't want a thread to be killed in the middle of some critical operation. You need to check for it.

CancellationTokens are better than simpler constructs like a ManualResetEvent for signalling shutdown of an operation because you can cascade or combine them, for example, you can have one for overall application shutdown and you can combine it with one for canceling a particular task. The task only has to look at the one CancellationToken but you can cancel it from either CancellationTokenSource.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!