在没有建造快速试验台的情况下;我想我会很快问,看看是否有人知道这个答案.
假设我有一个长期存在的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