加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 01:57:42 所属栏目:百科 来源:网络整理
导读:在没有建造快速试验台的情况下;我想我会很快问,看看是否有人知道这个答案. 此外,它可能具有通知可能遇到类似情况的其他用户的额外好处. 假设我有一个长期存在的CancellationTokenSource,其中许多不同的组件在CancellationToken上注册处理程序. 如果请求取消
在没有建造快速试验台的情况下;我想我会很快问,看看是否有人知道这个答案.

此外,它可能具有通知可能遇到类似情况的其他用户的额外好处.

假设我有一个长期存在的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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读