我为什么要使用CancellationToken.ThrowIfCancellationRequested?

时间:2018-05-14 13:29:37

标签: .net multithreading asynchronous clr

我有以下示例应用程序:

using System;
using System.Threading;
using static System.Threading.Thread;
using static System.Console;

internal static class ThreadCancellation
{
    private static void Main()
    {
        var cancellationTokenSource = new CancellationTokenSource();
        var cancellationToken = cancellationTokenSource.Token;
        ThreadPool.QueueUserWorkItem(x => Counter(cancellationToken));
        ThreadPool.QueueUserWorkItem(x => CounterWithThrow(cancellationToken));
        Sleep(10);
        cancellationTokenSource.Cancel();
        Sleep(10);
    }

    private static void Counter(CancellationToken cancellationToken)
    {
        WriteLine($"Counter running on {CurrentThread.ManagedThreadId}.");
        while (!cancellationToken.IsCancellationRequested)
        {
            WriteLine($"Thread {CurrentThread.ManagedThreadId}:  {DateTime.Now.Ticks}");
            Sleep(1);
        }

        WriteLine("Counter() was canceled");
    }

    private static void CounterWithThrow(CancellationToken cancellationToken)
    {
        WriteLine($"CounterWithThrow running on {CurrentThread.ManagedThreadId}.");

        try
        {
            while (true)
            {
                WriteLine($"Thread {CurrentThread.ManagedThreadId}:  {DateTime.Now.Ticks}");
                cancellationToken.ThrowIfCancellationRequested();
                Sleep(1);
            }

        }
        catch (OperationCanceledException e)
        {
            WriteLine($"Thread {CurrentThread.ManagedThreadId}: Caught OperationCanceledException: {e.Message}");
        }
    }
}

我期望它和输出的工作:

Counter running on 4.
CounterWithThrow running on 3.
Thread 4:  636619039468459034
Thread 3:  636619039468459034
Thread 4:  636619039468530368
Thread 3:  636619039468530368
Thread 4:  636619039468550400
Counter() was canceled
Thread 3:  636619039468550400
Thread 3: Caught OperationCanceledException: The operation was canceled.

为什么我会选择OperationCancelledException选项?

  1. 这应该是一个例外吗?
  2. catch中整理比在优雅地进行整理要困难得多。
  3. 如果我确实想要这样做,用if声明来实现它将是微不足道的。
  4. 鉴于这可能是有充分理由的,那是什么原因?

0 个答案:

没有答案