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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…