c# – 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

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...