我正在使用.net的HostBuilder编写后台服务。我有一个名为MyService的类,该类实现BackgroundService ExecuteAsync方法,并且在那里遇到了一些奇怪的行为。在方法内部,我等待某个任务,并且吞没了在等待之后引发的任何异常,但是在等待终止过程之前引发的异常。
我在各种论坛(堆栈溢出,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);
}
}
Run Code Online (Sandbox Code Playgroud)
我希望这两个异常都会终止该过程
c# background-service task-parallel-library async-await .net-core