为什么的CancellationToken是分开的CancellationTokenSource?CancellationToken、CancellationTokenSource

2023-09-02 02:07:44 作者:水洗晴空

我在寻找的,为什么.NET的CancellationToken结构是除了CancellationTokenSource类推出的理由。我理解的如何的的API被使用,但也想了解的为什么的是这样设计的。

I'm looking for a rationale of why .NET CancellationToken struct was introduced in addition to CancellationTokenSource class. I understand how the API is to be used, but want to also understand why it is designed that way.

即,为什么我们的:

var cts = new CancellationTokenSource();
SomeCancellableOperation(cts.Token);

...
public void SomeCancellableOperation(CancellationToken token) {
    ...
    token.ThrowIfCancellationRequested();
    ...
}

而不是直接通过CancellationTokenSource周围像:

instead of directly passing CancellationTokenSource around like:

var cts = new CancellationTokenSource();
SomeCancellableOperation(cts);

...
public void SomeCancellableOperation(CancellationTokenSource cts) {
    ...
    cts.ThrowIfCancellationRequested();
    ...
}

这是基于一个事实,即取消国家抽查发生的频率要高于周围传递令牌的性能优化?

Is this a performance optimization based on the fact that cancellation state checks happen more frequently than passing the token around?

这样CancellationTokenSource可以跟踪和更新CancellationTokens,并为每个标记取消检查是本地外地访问?

So that CancellationTokenSource can keep track of and update CancellationTokens, and for each token the cancellation check is a local field access?

由于挥发性布尔没有锁定足够在这两种情况下,我还是不明白为什么这将是更快的。

Given that a volatile bool with no locking is enough in both cases, I still can't see why that would be faster.

谢谢!

推荐答案

我参与设计这些类和实施。

I was involved in design and implementation of these classes.

简短的回答是关注点分离。这是很真实的,有不同的实现策略,有些是关于类型系统和初步学习简单的最少。然而,CTS和CT打算用在很多情况下(如深图书馆的书库,并行计算,异步等),因此在设计上有许多复杂的用例的初衷。它的目的是鼓励成功的模式,阻止反模式又不影响性能的设计。

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 of the cancellation design could quickly be eroded.

相关推荐