Why CancellationToken is separate from CancellationTokenSource?

后端 未结 5 1318
夕颜
夕颜 2020-12-02 06:22

I\'m looking for a rationale of why .NET CancellationToken struct was introduced in addition to CancellationTokenSource class. I understand how

5条回答
  •  无人及你
    2020-12-02 07:12

    They are separate not for technical reasons but semantic ones. If you look at the implementation of CancellationToken under ILSpy, you'll find it's merely a wrapper around CancellationTokenSource (and thus no different performance-wise than passing around a reference).

    They provide this separation of functionality to make things more predictable: when you pass a method a CancellationToken, you know you're still the only one that can cancel it. Sure, the method could still throw a TaskCancelledException, but the CancellationToken itself -- and any other methods referencing the same token -- would remain safe.

提交回复
热议问题