Task.WaitAll在任务故障执行时仍然被阻止

时间:2018-03-21 12:16:30

标签: c# .net

我有以这种方式创建的任务:

public static Task<T> RunAsync<T>(Func<T> function, CancellationToken token) {
     if (function == null) throw new ArgumentNullException("");
     var tcs = new TaskCompletionSource<T>();
     ThreadPool.QueueUserWorkItem(_ => {
        try {
           T result = function();
           tcs.SetResult(result);
        }
        catch (Exception exc) { tcs.TrySetException(exc); }
     }, token);
     return tcs.Task;
  }

我在此方法之后添加任务列表。 在System.Timer事件中,我检查任务的执行以启用/禁用这样的按钮:

 if (this.Tasks.Count > 0) {
        Task.WaitAll(this.Tasks.ToArray(), this.cancToken);
        this.BeginInvoke(new Action(() => EnableControls()));
        this.Task.Clear();
     }

好吧,如果任务正确完成,一切正常,但如果任务通过cancellationToken生成异常并且状态在“故障”中发生变化,那么WaitAll仍会被阻止。为什么?我无法理解。

我已在我的任务功能中提出取消,如下所示:

   if (cancToken.IsCancellationRequested)
     this.cancToken.ThrowIfCancellationRequested();

感谢。

0 个答案:

没有答案
相关问题