0

當執行</p> ​​ <p>的<code>try</code><code>catch</code>塊不處理<code>exception</code>這段代碼如何捕捉CancellationToken.ThrowIfCancellationRequested

public EnumerableObservable(IEnumerable<T> enumerable) 
    { 
     this.enumerable = enumerable; 
     this.cancellationSource = new CancellationTokenSource(); 
     this.cancellationToken = cancellationSource.Token; 


     this.workerTask = Task.Factory.StartNew(() => 
     { 
      try 
      { 
       foreach (var value in this.enumerable) 
       { 
        //if task cancellation triggers, raise the proper exception 
        //to stop task execution 

        cancellationToken.ThrowIfCancellationRequested(); 

        foreach (var observer in observerList) 
        { 
         observer.OnNext(value); 
        } 
       } 
      } 
      catch (AggregateException e) 
      { 
       Console.Write(e.ToString());      
      } 
     }, this.cancellationToken); 

    } 
+4

Catch'OperationCanceledException' – JSteward

回答

0

AggregateExceptions當在異步操作的例外可能發生大量拋出。它們包含所有例外情況,例如鏈接Tasks(通過。ContinueWith)或級聯async/await調用。

正如@Mitch Stewart指出的那樣,在你的例子中,正確的例外類型是OperationCancelledException

+1

實際上,如果引發異常的標記與傳遞給該標記的標記是相同的,那麼如果使用該異常,它將使'workerTask.IsCanceled == true' 'Task.Run'或'Task.Factory.StartNew' –

+0

當然,但是隨着優雅的取消,人們可以更好地控制異步執行的實際終止。 爲什麼TPL開發團隊首先實施Cancellatio基礎架構有很多很好的理由,因爲前者的線程模型並沒有提供默認的機制。 另請參閱本文後從2004年回覆[爲什麼Thread.Abort是邪惡的](http://www.interact-sw.co.uk/iangblog/2004/11/12/cancellation) –

+2

我不明白你的評論。使用'ThrowIfCancellationRequested' [被認爲是優雅的取消](https://msdn.microsoft.com/en-us/library/dd997364(v = vs.110).aspx)。不知道你爲什麼提出了Thread.Abort。 –

相關問題