0

我遇到了一种情况,即Task.Delay()方法会在IApplicationLifetime. 这是代码:

    static async Task Main(string[] args)
    {
        Console.WriteLine("Starting");

       await BuildWebHost(args)
            .RunAsync();
        
        Console.WriteLine("Press any key to exit..");
        Console.ReadKey();
    }

    private static IHost BuildWebHost(string[] args)
    {
        var hostBuilder = new HostBuilder()
            .ConfigureHostConfiguration(config =>
            {
                config.AddEnvironmentVariables();
                config.AddCommandLine(args);
            })
            .ConfigureAppConfiguration((hostContext, configApp) =>
            {
                configApp.SetBasePath(Directory.GetCurrentDirectory());
                configApp.AddCommandLine(args);
            })
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<BrowserWorkerHostedService>();
                services.AddHostedService<EmailWorkerHostedService>();
            })
            .UseConsoleLifetime();

        return hostBuilder.Build();
    }

以下是异常停止的托管服务:

public class BrowserWorkerHostedService : BackgroundService
{
    private IApplicationLifetime _lifetime;
    private IHost _host;

    public BrowserWorkerHostedService(
        IApplicationLifetime lifetime,
        IHost host)
    {
        this._lifetime = lifetime;
        this._host = host;
    }

    protected override async Task ExecuteAsync(CancellationToken stopToken)
    {
        while (!_lifetime.ApplicationStarted.IsCancellationRequested
            && !_lifetime.ApplicationStopping.IsCancellationRequested
            && !stopToken.IsCancellationRequested)
        {
            Console.WriteLine($"{nameof(BrowserWorkerHostedService)} is working. {DateTime.Now.ToString()}");
            
            //lifetime.StopApplication();
            //await StopAsync(stopToken);

            await Task.Delay(1_000, stopToken);
        }

        Console.WriteLine($"End {nameof(BrowserWorkerHostedService)}");

        await _host.StopAsync(stopToken);
    }
}

public class EmailWorkerHostedService : BackgroundService
{
    private IApplicationLifetime _lifetime;
    private IHost _host = null;

    public EmailWorkerHostedService(
        IApplicationLifetime lifetime,
        IHost host)
    {
        this._lifetime = lifetime;
        this._host = host;
    }

    protected override async Task ExecuteAsync(CancellationToken stopToken)
    {
        while (!_lifetime.ApplicationStarted.IsCancellationRequested
            && !_lifetime.ApplicationStopping.IsCancellationRequested
            && !stopToken.IsCancellationRequested)
        {
            Console.WriteLine($"{nameof(EmailWorkerHostedService)} is working. {DateTime.Now.ToString()}");

            await Task.Delay(1_000, stopToken);
        }

        Console.WriteLine($"End {nameof(EmailWorkerHostedService)}");
        
        await _host.StopAsync(stopToken);
    }
}

我希望我的服务能够运行,除非lifetime.StopApplication()被触发。但是,托管服务已停止,因为lifetime.ApplicationStarted.IsCancellationRequested变量true在第二次迭代时设置为。尽管理论上,我没有明确中止应用程序的代码。

日志将如下所示:

启动 BrowserWorkerHostedService 正在工作。09.07.2019 17:03:53

EmailWorkerHostedService 正在工作。09.07.2019 17:03:53

申请开始。按 Ctrl+C 关闭。

托管环境:生产

内容根路径:xxxx

结束 EmailWorkerHostedService

结束 BrowserWorkerHostedService

有没有很好的解释为什么Task.Delay()触发 ApplicationStarted 取消事件?

4

1 回答 1

1

你在滥用IApplicationLifetime事件。他们的目的是让你能够将一些行动与他们联系起来。例如,您希望仅在应用程序完全启动时才启动消息队列侦听。你要这样做:

_applicationLifetime.ApplicationStarted. Register(StartListenMq);

我认为CancellationTokens在这里使用不是最好的主意,但它的实现方式。

当您想取消时,HostedService您应该只检查ExecuteAsync方法中收到的令牌。流程看起来像这样:

IApplicationLifetime.StopApplication()=> 将触发IApplicationLifetime.ApplicationStopping=> 将触发IHostedService.StopAsync()=> 将stopToken

现在问你的问题:为什么会发生在await Task.Delay()? 再看看 BackgroundService.StartAsync()

    public virtual Task StartAsync(CancellationToken cancellationToken)
    {
        // Store the task we're executing
        _executingTask = ExecuteAsync(_stoppingCts.Token);

        // If the task is completed then return it, this will bubble cancellation and failure to the caller
        if (_executingTask.IsCompleted)
        {
            return _executingTask;
        }

        // Otherwise it's running
        return Task.CompletedTask;
    }

此代码等待ExecuteAsync。此时您在代码中调用异步操作StartAsync()将继续运行。在它的调用堆栈中的某个地方它会触发ApplicationStarted,因为你正在听它,你会得到_lifetime.ApplicationStarted.IsCancellationRequested = true.

于 2019-07-09T16:47:08.523 回答