我想獲得異步/等待和TPL的堅實把握,所以我正在嘗試一些事情。我發現有很多類似的問題,但我仍然無法弄清楚這裏發生了什麼。道歉,如果我失去了一些明顯的或已經回答的問題。任務ContinueWith OnlyOnFaulted仍然得到CurrentDomain.UnhandledException異常
如果你不喜歡vb.net請convert it;)
爲什麼CurrentDomain.UnhandledException仍時有發生?我認爲它會被觀察當我訪問task.Exception並在句柄中返回true,並且因爲它被觀察到它不會自動傳播?
Public Function ContinueWith_ExceptionHandling_Flattening() As Threading.Tasks.Task(Of Integer)
Dim s As String = "ContinueWith_ExceptionHandling_Flattening"
Dim context = TaskScheduler.FromCurrentSynchronizationContext()
AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf CurrentDomain_UnhandledException
Dim t As Task(Of Integer) = Task.Run(Function() ThrowException(0, ""))
t.ContinueWith(Function(a) CreateAndShowResultForm(a.Result, s), Threading.CancellationToken.None, TaskContinuationOptions.NotOnFaulted, context) 'doesnt run if t faulted!
t.ContinueWith(AddressOf HandleTask_Exception, Threading.CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, context) 'only runs if t faulted
Return t
End Function
Private Sub HandleTask_Exception(x As task)
x.Exception.Flatten.Handle(Function(ex)
Select Case ex.GetType
Case GetType(NoNullAllowedException)
MessageBox.Show("NoNullAllowedException ...handled by HandleTask_Exception")
Case Else
MessageBox.Show(ex.Message & " ...handled by HandleTask_Exception")
End Select
Return True
End Function)
End Sub
'THIS IS STILL BEING HIT (I am looking for explanation as to why)
Private Sub CurrentDomain_UnhandledException(sender As Object, e As UnhandledExceptionEventArgs)
MessageBox.Show("CurrentDomain_UnhandledException: " & CType(e.ExceptionObject, Exception).Message)
End Sub
'Calling code
Public Async Function ContinueWith_ExceptionHandling_Flattening_Helper() As Task(Of Integer)
Return Await cls.ContinueWith_ExceptionHandling_Flattening
End Function
很有趣的是你的源代碼是在VB.Net,但你標記的C#,甚至沒有標註Vb.Net O_O – 2015-02-09 21:17:55
我最後一次標記爲vb.net。和C#和管理員刪除我的vb.net標籤,並離開了C#。 – HeatherD 2015-02-09 21:27:20
您應該注意,未觀察到的任務異常不會導致引發'UnhandledException'。這個事件在'async void'方法和線程中未處理的異常中引發。 – i3arnon 2015-02-09 21:31:45