什么是TaskFactory.StartNew()中的"cancellationToken"用于?

zer*_*kms 16 c# multithreading cancellation-token

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();
    }
Run Code Online (Sandbox Code Playgroud)

UPD:嗯,这只是改变task.IsCanceled,这是无用的,因为我仍然应该手动实现所有.

Vir*_*usX 35

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

请考虑以下代码:

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

tokenSource.Cancel(); 

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

即使tokenSource.Cancel()在实际启动任务之前发出调用,您仍将从线程池中分配工作线程,因此您将浪费一些系统资源.

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

  • 这应该是接受的答案 - 代表您上面发布.一个问题 - 是否有办法获取传入的当前任务的取消令牌?有点像Dispatcher.CurrentDispatcher? (2认同)
  • 这困难了很长一段时间.是否有任何MSDN文档证实了这一点? (2认同)