.Net 6.0 BackgroundService.ExecuteAsync stoppingToken/Exception异常

xcitsw88  于 2023-06-07  发布在  .NET
关注(0)|答案(1)|浏览(162)

我正在尝试使用.Net 6中的基本Worker模板。在我按Ctrl-C退出时,使用默认实现,ExecuteAsync中while循环之后的代码永远不会被命中。我添加了异常处理,果然,只要我按下Ctrl-C,我就得到了异常,它记录了消息“Execute Cancelled”。奇怪的是,在我添加异常处理代码之前,应用程序“干净”地退出,即控制台中没有显示异常。现在代码已经在那里了,就在我看到日志消息之后,它也显示了一个异常,就好像我没有捕捉到它一样。
下面是我正在使用的代码:

public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;

        public Worker(ILogger<Worker> logger)
        {
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await Task.Yield();

            try
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    _logger.LogInformation($"Worker running at: {DateTimeOffset.Now} / Cancel: {stoppingToken.IsCancellationRequested}");
                    await Task.Delay(1000, stoppingToken);
                }
// THIS CODE NEVER EXECUTES
                _logger.LogInformation("Execution ended. Cancelation token cancelled = {IsCancellationRequested}",stoppingToken.IsCancellationRequested);
            }
            catch (Exception ex) when (stoppingToken.IsCancellationRequested)
            {
                _logger.LogWarning(ex, "Execution Cancelled");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Unhandeled exception. Execution Stopping");
            }
        }

    }

带有异常处理的输出:

info: WorkerService1.Worker[0]
      Worker running at: 6/6/2023 1:10:08 PM -04:00 / Cancel: False
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: C:\Users\jangi\source\repos\WorkerService1
info: WorkerService1.Worker[0]
      Worker running at: 6/6/2023 1:10:09 PM -04:00 / Cancel: False
info: WorkerService1.Worker[0]
      Worker running at: 6/6/2023 1:10:10 PM -04:00 / Cancel: False
info: WorkerService1.Worker[0]
      Worker running at: 6/6/2023 1:10:11 PM -04:00 / Cancel: False
info: Microsoft.Hosting.Lifetime[0]
      Application is shutting down...
warn: WorkerService1.Worker[0]
      Execution Cancelled
      System.Threading.Tasks.TaskCanceledException: A task was canceled.
         at WorkerService1.Worker.ExecuteAsync(CancellationToken stoppingToken) in C:\Users\jangi\source\repos\WorkerService1\Worker.cs:line 23

无异常处理的输出:

info: WorkerService1.Worker[0]
      Worker running at: 6/6/2023 1:14:30 PM -04:00 / Cancel: False
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: C:\Users\jangi\source\repos\WorkerService1
info: WorkerService1.Worker[0]
      Worker running at: 6/6/2023 1:14:31 PM -04:00 / Cancel: False
info: WorkerService1.Worker[0]
      Worker running at: 6/6/2023 1:14:32 PM -04:00 / Cancel: False
info: WorkerService1.Worker[0]
      Worker running at: 6/6/2023 1:14:33 PM -04:00 / Cancel: False
info: Microsoft.Hosting.Lifetime[0]
      Application is shutting down...

我在网上到处都是,我能找到的每一个例子都显示出与我所看到的不同的行为。

cld4siwp

cld4siwp1#

您正在使用已取消的令牌创建Task.Delay

await Task.Delay(1000, stoppingToken);

方法在取消令牌时引发TaskCanceledException

相关问题