Cancelling a Task is throwing an exception

后端 未结 5 2082
[愿得一人]
[愿得一人] 2020-11-27 03:52

From what I\'ve read about Tasks, the following code should cancel the currently executing task without throwing an exception. I was under the impression that the whole poin

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 04:18

    Another note about the benefit of using ThrowIfCancellationRequested rather than IsCancellationRequested: I've found that when needing to use ContinueWith with a continuation option of TaskContinuationOptions.OnlyOnCanceled, IsCancellationRequested will not cause the conditioned ContinueWith to fire. ThrowIfCancellationRequested, however, will set the Canceled condition of the task, causing the ContinueWith to fire.

    Note: This is only true when the task is already running and not when the task is starting. This is why I added a Thread.Sleep() between the start and cancellation.

    CancellationTokenSource cts = new CancellationTokenSource();
    
    Task task1 = new Task(() => {
        while(true){
            if(cts.Token.IsCancellationRequested)
                break;
        }
    }, cts.Token);
    task1.ContinueWith((ant) => {
        // Perform task1 post-cancellation logic.
        // This will NOT fire when calling cst.Cancel().
    }
    
    Task task2 = new Task(() => {
        while(true){
            cts.Token.ThrowIfCancellationRequested();
        }
    }, cts.Token);
    task2.ContinueWith((ant) => {
        // Perform task2 post-cancellation logic.
        // This will fire when calling cst.Cancel().
    }
    
    task1.Start();
    task2.Start();
    Thread.Sleep(3000);
    cts.Cancel();
    

提交回复
热议问题