text 实现IHostedService用于实现后台服务,类似while(true)的基类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text 实现IHostedService用于实现后台服务,类似while(true)的基类相关的知识,希望对你有一定的参考价值。

 public abstract class HostedService : IHostedService
    {


        private Task _executingTask;
        private CancellationTokenSource _cts;

        public Task StartAsync(CancellationToken cancellationToken)
        {
            // Create a linked token so we can trigger cancellation outside of this token's cancellation
            _cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

            // Store the task we're executing
            _executingTask = ExecuteAsync(_cts.Token);

            // If the task is completed then return it, otherwise it's running
            return _executingTask.IsCompleted ? _executingTask : Task.CompletedTask;
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            // Stop called without start
            if (_executingTask == null)
            {
                return;
            }

            // Signal cancellation to the executing method
            _cts.Cancel();

            // Wait until the task completes or the stop token triggers
            await Task.WhenAny(_executingTask, Task.Delay(-1, cancellationToken));

            // Throw if cancellation triggered
            cancellationToken.ThrowIfCancellationRequested();
        }

        // Derived classes should override this and execute a long running method until 
        // cancellation is requested
        protected abstract Task ExecuteAsync(CancellationToken cancellationToken);
    }

以上是关于text 实现IHostedService用于实现后台服务,类似while(true)的基类的主要内容,如果未能解决你的问题,请参考以下文章

.NET Core 实现后台任务(定时任务)IHostedService

IHostedService 可用于 Azure Functions 应用程序吗?

用于后台任务的asp.net框架中的Ihostedservice等价物

在后台主机中托管SignalR服务并广播心跳包

如何在 ASP.Net Core 中使用 IHostedService

我应该如何将 DbContext 实例注入 IHostedService?