Вопрос по multithreading, .net, c# – Какая польза от передачи CancellationToken в конструктор класса задач?

19

Error: User Rate Limit Exceeded

       CancellationTokenSource CTS= new CancellationTokenSource();

       Task<Boolean> PTask = new Task<Boolean>(() => 
       {
           while (true)
           {
               if (!CTS.Token.IsCancellationRequested)
               {
                  Thread.Sleep(5000);
               }
               else{Console.WriteLine("Thread Cancelled");break;}
           }
           return true;

       }, CTS.Token, TaskCreationOptions.None);

       PTask.Start();
       Console.WriteLine("Hit Enter to cancel the Secondary thread you have started");
       Console.ReadLine();
       CTS.Cancel();
       System.Console.WriteLine(PTask.Result);

    }
}

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

      CancellationTokenSource CTS= new CancellationTokenSource();
      Task<Boolean> PTask = new Task<Boolean>(() => 
       {
           while (true)
           {
               if (!CTS.Token.IsCancellationRequested)
               {
                   Thread.Sleep(5000);
               }
               else
               {
                   Console.WriteLine("Thread Cancelled");
                   break;
               }
       };
Error: User Rate Limit Exceededblogs.msdn.com/b/pfxteam/archive/2009/05/22/9635790.aspx Slugart

Ваш Ответ

1   ответ
35

Passing a token into StartNew associates the token with the Task. This has two primary benefits:

If the token has cancellation requested prior to the Task starting to execute, the Task won't execute. Rather than transitioning to Running, it'll immediately transition to Canceled. This avoids the costs of running the task if it would just be canceled while running anyway.

If the body of the task is also monitoring the cancellation token and throws an OperationCanceledException containing that token (which is what ThrowIfCancellationRequested does), then when the task sees that OCE, it checks whether the OCE's token matches the Task's token. If it does, that exception is viewed as an acknowledgement of cooperative cancellation and the Task transitions to the Canceled state (rather than the Faulted state).

Error: User Rate Limit Exceeded
Error: User Rate Limit ExceededTask.Run(async () => { throw new OperationCanceledException(); }, new CancellationToken(false)).ContinueWith(tsk => Console.WriteLine(tsk.Status))Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded Prabhu Murthy
Error: User Rate Limit Exceeded

Похожие вопросы