Skip to main content
 首页 » 编程设计

c#中CancellationToken.Register 作为事件通知机制与标准 .NET 事件模式

2025年12月25日40zhenyulu

C#中,尽管最初的想法是the new cancellation framework使用 CancellationToken.Register 来通知取消操作,它也可以用作简单事件通知的机制。

我们以 IApplicationLifetime 为例及其实现 ASP.NET/Hosting .

ApplicationLifetime 的精简版如下所示:

/// <summary> 
/// Allows consumers to perform cleanup during a graceful shutdown. 
/// </summary> 
public class ApplicationLifetime : IApplicationLifetime 
{ 
    private readonly CancellationTokenSource _startedSource = new CancellationTokenSource(); 
 
    /// <summary> 
    /// Triggered when the application host has fully started and is about to wait 
    /// for a graceful shutdown. 
    /// </summary> 
    public CancellationToken ApplicationStarted => _startedSource.Token; 
 
    /// <summary> 
    /// Signals the ApplicationStarted event and blocks until it completes. 
    /// </summary> 
    public void NotifyStarted() 
    { 
        _startedSource.Cancel(throwOnFirstException: false); 
    } 
} 

客户端可以注册应用程序启动通知并执行某些操作,不一定是取消操作。

lifetime.ApplicationStarted.Register(() => 
{ 
    Console.WriteLine("Started"); 
}); 

然后请求对象可以触发通知:

_applicationLifetime?.NotifyStarted(); 

基本上,使用 standardupdated .NET 事件模式可以实现几乎相同的效果。或者,我错过了什么吗?

从架构的角度来看,这两种方法有什么区别?优点和缺点?何时使用其中之一?

CancellationToken.Register 作为简单事件通知的机制只是模式的“创造性”使用吗?

请您参考如下方法:

取消 token 的目的是帮助解决多线程代码中的故障状态。有一些与使用取消机制的任务相关的内置方法,因此如果您使用相同的方法,您可以让您的代码与它们无缝协作。使用标准方法可以更轻松地编写库代码,因为它可以假设调用者正在使用相同的方法。

标准 .NET 事件机制不了解线程,因此如果存在潜在问题,您需要处理可能的多线程问题。在简单的情况下,.NET 偶数机制可以正常工作。如果您自己的场景更复杂,那么您应该考虑使用取消 token 方法。