简体   繁体   English

asp .net 核心中 IHostedService.StartAsync 中的 CancellationToken 有什么意义?

[英]What is the point of the CancellationToken in IHostedService.StartAsync in asp .net core?

I'm trying to implement a hosted service and I was wondering what I am expected to do with the CancellationToken in the IHostedService.StartAsync call.我正在尝试实现托管服务,我想知道我应该对IHostedService.StartAsync调用中的 CancellationToken 做什么。

There is quite a lot in the Microsoft documentation about the cancellation token in StopAsync being essentially a timeout (5s by default) that means graceful shutdown is supposed to happen within a reasonable timeframe. Microsoft 文档中有很多关于StopAsync的取消令牌本质上是超时(默认为 5 秒),这意味着正常关闭应该在合理的时间范围内发生。

But regarding the token in StartAsync , there is not much information.但是关于StartAsync的令牌,没有太多信息。 If anything, the documentation specifies that the implementation shouldn't await on long running initialisation processes and should just return a long running task.如果有的话,文档指定实现不应该等待长时间运行的初始化过程,而应该只返回一个长时间运行的任务。 So if I support cancellation, should I pass the cancellation token to whatever creates that long running task?因此,如果我支持取消,我是否应该将取消令牌传递给创建该长时间运行任务的任何内容? If yes, isn't cancelling this token a dumber version of StopAsync ?如果是,取消此令牌不是StopAsync版本吗? Why would the framework ever do this?为什么框架会这样做?

And indeed, in Microsoft's own abstract BackgroundService , the implementation for StartAsync actually completely ignores that token and creates a new one which will be cancelled on call to StopAsync ...事实上,在微软自己的抽象BackgroundService ,为实现StartAsync实际上完全忽略了该令牌,并创建一个新的,这在呼叫被取消StopAsync ...

So am I to think that the whole point of that initial token passed by the framework is actually to be used in blocking initialisation processes nonetheless (despite the doc advising against it) by overriding the virtual BackgroundService.StartAsync method?那么我是否认为框架传递的初始令牌的全部意义实际上是通过覆盖虚拟BackgroundService.StartAsync方法来阻止初始化过程(尽管文档反对它)? eg例如

public class MyBackgroundService : BackgroundService
{
    public override Task StartAsync(CancellationToken cancellationToken)
    {
        // Block the thread for initialisation with cancellation (replace Task.Delay by actual initialisation)
        Task.Delay(TimeSpan.FromSeconds(10), cancellationToken).GetAwaiter().GetResult();

        // Start the long running task proper
        return base.StartAsync(cancellationToken);
    }

    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        // some long running process (write some actual background running code here)
        return Task.Factory.StartNew(_ => {while(!stoppingToken.IsCancellationRequested){}}, null, stoppingToken);
    }
}

The CancellationToken passed into the StartAsync can be used to determine if the start process should be canceled but as far as I understand, you already know that.传递给StartAsyncCancellationToken可用于确定是否应取消启动过程,但据我所知,您已经知道了。 This is written here .这是写在这里

Indicates that the start process has been aborted.表示启动过程已中止。

If you look at where StartAsync is called , you can see that the CancellationToken which is passed into the StartAsync function is linked with IHostApplicationLifetime.ApplicationStopping .如果你看一下哪里StartAsync,你可以看到CancellationToken被传递到StartAsync功能相链接IHostApplicationLifetime.ApplicationStopping As far as I understand, this token is just used if the shutdown of the application happens so early that not all hosted services have been fully started yet.据我了解,如果应用程序关闭太早以至于并非所有托管服务都已完全启动,则仅使用此令牌。 However, I don't know if StopAsync will be called if the starting token is triggered (I'd have to dig further in the sources or search more in the docs).但是,我不知道是否会在触发起始令牌时调用StopAsync (我必须在源代码中进一步挖掘或在文档中搜索更多内容)。

To summarize:总结一下:
The CancellationToken in the StartAsync -method should just be passed to any method called in StartAsync which supports cancellation. StartAsync方法中的CancellationToken应该只传递给在StartAsync中调用的任何支持取消的方法。 It will allow the app to shutdown gracefully in case the requested shutdown happens so early that the hosted service has not been fully started yet.如果请求的关闭发生得太早以至于托管服务尚未完全启动,它将允许应用正常关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 IHostedService.StartAsync 期间请求应用程序停止导致未处理的 TaskCanceledException - Requesting for application to stop during IHostedService.StartAsync results in an unhandled TaskCanceledException 如何在 ASP.Net Core 中使用 IHostedService? - How to use IHostedService in ASP.Net Core? ASP.NET Core ActionFilter 中是否提供 CancellationToken? - Is CancellationToken available in ASP.NET Core ActionFilter? CancellationToken 在 asp.net 核心中不起作用 - CancellationToken not working in asp.net core 在 .NET Core 5 的托管服务的 StartAsync 和 StopAsync 中返回什么? - What to return in StartAsync and StopAsync of a hosted service for .NET Core 5? 使用ASP.NET Core 2.0将简单的Injector组件注入IHostedService - Injecting Simple Injector components into IHostedService with ASP.NET Core 2.0 ASP.NET 核心 IHostedService 手动启动/停止/暂停(?) - ASP.NET Core IHostedService manual start/stop/pause(?) StartAsync 在同一个 IHostedService 上被调用两次 - StartAsync is called twice on the same IHostedService .NET Core 中 tcp 服务器的 IHostedService - IHostedService for tcp servers in .NET Core 在 ASP.NET Core 上配置 DefaultScheme 和 DefaultChallengeScheme 有什么意义? - What is the point of configuring DefaultScheme and DefaultChallengeScheme on ASP.NET Core?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM