从Task.Delay()中取消异常

时间:2017-02-10 06:41:02

标签: c# multithreading exception-handling async-await cancellation-token

我有一个异步任务和一个Task.Delay(时间,令牌)。我从主线程中等待对该方法的调用。每当取消令牌为真,它就会破坏我的主线程。我需要处理/避免Task.Delay()中的任何异常。有可能吗?

代码段:

protected override async Task RunAsync(CancellationToken cancellationToken)
    {
        await StartHealthMonitorAsync(cancellationToken);
    }

private async Task StartWorkAsync(CancellationToken cancellationToken)
    {
        var delaySpan = TimeSpan.FromMinutes(1);
        while (!cancellationToken.IsCancellationRequested)
        {
            await Task.Delay(delaySpan, cancellationToken);
            await someTask.DoWorkAsync(cancellationToken);
        }
    }

感谢

1 个答案:

答案 0 :(得分:1)

  

我需要处理/避免Task.Delay()中的任何异常。有可能吗?

是。使用catch

protected override async Task RunAsync(CancellationToken cancellationToken)
{
    await StartWorkAsync(cancellationToken);
}

private async Task StartWorkAsync(CancellationToken cancellationToken)
{
  var delaySpan = TimeSpan.FromMinutes(1);
  try
  {
    while (true)
    {
      await Task.Delay(delaySpan, cancellationToken);
      await someTask.DoWorkAsync(cancellationToken);
    }
  }
  catch (OperationCanceledException)
  {
  }
}

我还删除了IsCancellationRequested的额外支票,因为没有必要。