gpt4 book ai didi

c# - CancellationToken - 请求取消后注册处理程序

转载 作者:行者123 更新时间:2023-11-30 13:46:56 24 4
gpt4 key购买 nike

在没有搭建快速测试台的情况下;我想我会很快问 SO 看看是否有人知道这个答案。

此外,它可能还有一个额外的好处,即通知可能遇到类似情况的其他用户。

假设我有一个长期存在的 CancellationTokenSource,其中有许多不同的组件在 CancellationToken 上注册处理程序。

如果请求取消并且所有已注册的回调都被调用,然后在该点之后注册另一个处理程序;注册时新回调的取消回调是否仍会触发?

提前干杯!

最佳答案

查看 CancellationToken.Register 的文档:

If this token is already in the canceled state, the delegate will be run immediately and synchronously. Any exception the delegate generates will be propagated out of this method call.

The current ExecutionContext, if one exists, will be captured along with the delegate and will be used when executing it.

考虑以下几点:

void RegisterBeforeCancel(CancellationToken token)
{
token.Register(() => Console.WriteLine("Before cancel"));
}

void RegisterAfterCancel(CancellationToken token)
{
token.Register(() => Console.WriteLine("After cancel"));
}

var cts = new CancellationTokenSource();

RegisterBeforeCancel(cts.Token);

cts.Cancel();

RegisterAfterCancel(cts.Token);

输出将显示:

Before cancel
After cancel

关于c# - CancellationToken - 请求取消后注册处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19317658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com