首页 > 解决方案 > 如果在“等待”之后抛出,则从任务中抛出的异常被吞没

问题描述

我正在使用 .NET 编写后台服务HostBuilder。我有一个名为MyService实现BackgroundService ExecuteAsync方法的类,我在那里遇到了一些奇怪的行为。在方法内部我await执行了某个任务,并且在吞下之后抛出的任何异常,但是在终止进程await之前抛出的异常。await

我在各种论坛(堆栈溢出、msdn、中等)上查看了在线信息,但找不到这种行为的解释。

public class MyService : BackgroundService
    {
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await Task.Delay(500, stoppingToken);
            throw new Exception("oy vey"); // this exception will be swallowed
        }
    }

public class MyService : BackgroundService
    {
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            throw new Exception("oy vey"); // this exception will terminate the process
            await Task.Delay(500, stoppingToken);
        }
    }

我希望这两个异常都会终止该过程。

标签: c#.net-coreasync-awaittask-parallel-librarybackground-service

解决方案


TL;博士;

不要让异常退出ExecuteAsync. 处理它们、隐藏它们或明确请求关闭应用程序。

在开始第一个异步操作之前不要等待太久

解释

这与它本身关系不大await。之后抛出的异常将冒泡给调用者。处理它们的是调用者,或者不是。

ExecuteAsync是一个调用的方法,BackgroundService这意味着该方法引发的任何异常都将由BackgroundService. 该代码是

    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;
    }

没有任何东西等待返回的任务,所以这里不会抛出任何东西。检查IsCompleted是一种优化,可避免在任务已完成时创建异步基础架构。

在调用StopAsync之前,不会再次检查该任务。那时任何异常都会被抛出。

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

        try
        {
            // Signal cancellation to the executing method
            _stoppingCts.Cancel();
        }
        finally
        {
            // Wait until the task completes or the stop token triggers
            await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite, cancellationToken));
        }

    }

从服务到主机

反过来,StartAsync每个服务的方法由 Host 实现的StartAsync方法调用。代码揭示了发生了什么:

    public async Task StartAsync(CancellationToken cancellationToken = default)
    {
        _logger.Starting();

        await _hostLifetime.WaitForStartAsync(cancellationToken);

        cancellationToken.ThrowIfCancellationRequested();
        _hostedServices = Services.GetService<IEnumerable<IHostedService>>();

        foreach (var hostedService in _hostedServices)
        {
            // Fire IHostedService.Start
            await hostedService.StartAsync(cancellationToken).ConfigureAwait(false);
        }

        // Fire IHostApplicationLifetime.Started
        _applicationLifetime?.NotifyStarted();

        _logger.Started();
    }

有趣的部分是:

        foreach (var hostedService in _hostedServices)
        {
            // Fire IHostedService.Start
            await hostedService.StartAsync(cancellationToken).ConfigureAwait(false);
        }

直到第一个真正的异步操作的所有代码都在原始线程上运行。当遇到第一个异步操作时,原始线程被释放。一旦该任务完成,之后的所有内容都await将恢复。

从主机到 Main()

Main() 中用于启动托管服务的RunAsync()方法实际上调用了主机的 StartAsync 而不是StopAsync :

    public static async Task RunAsync(this IHost host, CancellationToken token = default)
    {
        try
        {
            await host.StartAsync(token);

            await host.WaitForShutdownAsync(token);
        }
        finally
        {
#if DISPOSE_ASYNC
            if (host is IAsyncDisposable asyncDisposable)
            {
                await asyncDisposable.DisposeAsync();
            }
            else
#endif
            {
                host.Dispose();
            }

        }
    }

这意味着从 RunAsync 到第一个异步操作之前在链中引发的任何异常都会冒泡到启动托管服务的 Main() 调用:

await host.RunAsync();

或者

await host.RunConsoleAsync();

这意味着对象列表中第一个实数之前的所有内容都在原始线程上运行。除非处理,否则任何扔在那里的东西都会导致应用程序崩溃。由于or被调用,这就是应该放置块的位置。awaitBackgroundServiceIHost.RunAsync()IHost.StartAsync()Main()try/catch

这也意味着在第一个真正的异步操作之前放置慢代码可能会延迟整个应用程序。

第一次异步操作之后的所有内容都将继续在线程池线程上运行。这就是为什么在第一次操作之后抛出的异常不会冒泡,直到托管服务通过调用关闭IHost.StopAsync或任何孤立任务获得 GCd

结论

不要让异常逃脱ExecuteAsync。抓住它们并妥善处理它们。选项是:

  • 记录并“忽略”它们。这将使 BackgroundService 无效,直到用户或某些其他事件调用应用程序关闭。退出ExecuteAsync不会导致应用程序退出。
  • 重试操作。这可能是简单服务中最常见的选项。
  • 在排队或定时服务中,丢弃出错的消息或事件并移至下一个。这可能是最有弹性的选择。可以检查错误消息,将其移至“死信”队列,重试等。
  • 明确要求关机。为此,请将IHostedApplicationLifetTime接口添加为依赖项并从块中调用StopAsync 。catch这也将调用StopAsync所有其他后台服务

文档

托管服务的行为,BackgroundService使用 IHostedService 和 BackgroundService 类实现微服务中的后台任务和在 ASP.NET Core 中使用托管服务的后台任务中进行了描述。

文档没有解释如果其中一项服务抛出会发生什么。它们演示了具有显式错误处理的特定使用场景。排队后台服务示例丢弃导致故障的消息并移至下一个:

    while (!cancellationToken.IsCancellationRequested)
    {
        var workItem = await TaskQueue.DequeueAsync(cancellationToken);

        try
        {
            await workItem(cancellationToken);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, 
               $"Error occurred executing {nameof(workItem)}.");
        }
    }

推荐阅读