Why CancellationToken is separate from CancellationTokenSource?

后端 未结 5 1319
夕颜
夕颜 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:05

    I was involved in the design and implementation of these classes.

    The short answer is "separation of concerns". It is quite true that there are various implementation strategies and that some are simpler at least regarding the type system and initial learning. However, CTS and CT are intended for use in a great many scenarios (such as deep library stacks, parallel computation, async, etc) and thus was designed with many complex use cases in mind. It is a design intended to encourage successful patterns and discourage anti-patterns without sacrificing performance.

    If the door was left open for misbehaving APIs, then the usefulness of the cancellation design could quickly be eroded.

    CancellationTokenSource == "cancellation trigger", plus generates linked listeners

    CancellationToken == "cancellation listener"

提交回复
热议问题