How to safely cancel a task using a CancellationToken and await Task.WhenAll

前端 未结 2 1645
时光说笑
时光说笑 2021-01-25 07:18

I have a framework which creates a CancellationTokenSource, configures CancelAfter, then calls an async method and passes the Token. The async method then spawns many tasks, pas

2条回答
  •  执念已碎
    2021-01-25 08:21

    I recommend that you follow the standard cancellation pattern of throwing an exception rather than just returning:

    public static void DoWork(work, cancellationToken)
    {
      while (work.IsWorking)
      {
        cancellationToken.ThrowIfCancellationRequested();
        work.DoNextWork();
      }
    }
    

    If you have cleanup work to do, that's what finally is for (or using, if you can refactor that way):

    public async Task Run(CancellationToken cancellationToken)
    {
      HashSet tasks = new HashSet();
      foreach (var work in this.GetWorkNotPictured)
      {
        tasks.Add(Task.Run(() => this.DoWork(work, cancellationToken))
      }
    
      try
      {
        await Task.WhenAll(tasks);
      }
      finally
      {
        this.CleanUpAfterWork();
      }
    }
    

提交回复
热议问题