我正在努力掌握async / await和TPL,所以我正在尝试一些事情。我看到有很多类似的问题,但我仍然无法弄清楚这里发生了什么。如果我遗漏了一些明显或已经回答的问题,请道歉。
如果您不喜欢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
答案 0 :(得分:2)
在现代代码中,您应该使用await
而不是ContinueWith
。它比乱搞任务调度程序,聚合异常等等更容易:
public async Task<int> ContinueWith_ExceptionHandling_FlatteningAsync()
{
string s = "ContinueWith_ExceptionHandling_Flattening";
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Task<int> t = Task.Run(() => ThrowException(0, ""));
try
{
var result = await t;
CreateAndShowResultForm(result, s);
return result;
}
catch (Exception ex)
{
HandleTask_Exception(ex);
throw;
}
}
private void HandleTask_Exception(Exception ex)
{
MessageBox.Show(ex.Message + " ...handled by HandleTask_Exception");
}