IHostedService作为控制台应用程序

IHostedService作为控制台应用程序

本文介绍了关闭.Netcore IHostedService作为控制台应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在.netcore 2.2中构建了通用主机(IHostedService)。我正在以RunConsoleAsync()的身份运行HostBuilder。
RunConsoleAync()将等待Ctrl + C关闭应用程序。
我想在StartAsync()过程完成后立即关闭控制台应用程序,而不是用户必须按ctrl + c。

I have built Generic Host (IHostedService) in .netcore 2.2. I am running HostBuilder as RunConsoleAsync().RunConsoleAync() will wait for Ctrl + C to close application.I want to close console app as soon as StartAsync() process complete instead of user has to press ctrl + c.

我尝试调用StopAsync()

I tried to Invoke StopAsync() with new CancellationToken(true), but it is not helping me.

我将其开发为IHostedService,因为该应用程序将部署在多种平台上。

I developed this as IHostedService, because this app will be deployed on multiple plateform.

推荐答案

我假设您已经实现了 IHostedService 实现。您需要做的就是注入 IHostApplicationLifetime 并使用它来停止应用程序,如下所示:

I assume you have the IHostedService implementation in place. All you need to do is inject IHostApplicationLifetime and use that to stop the application as shown below:

    public class Service : IHostedService
{
    private readonly IHostApplicationLifetime _applicationLifetime;
    public Service(IHostApplicationLifetime applicationLifetime)
    {
        _applicationLifetime = applicationLifetime;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        ...

        _applicationLifetime.StopApplication();
        return Task.CompletedTask;
    }

    ...
}

这篇关于关闭.Netcore IHostedService作为控制台应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 09:01