使用 Tasks 解锁 UI 并且不能使用 Aync/Await 时,推荐的处理错误的方法是什么?
我通常希望通过更新 UI 来处理预期的错误,并在 Application_DispatcherUnhandledException 等全局错误处理程序中处理意外错误(记录异常、通知用户和关闭应用程序)。
我正在使用以下对我来说看起来很难看的方法。
Private Sub _showAsyncButton_Click(sender As Object, e As RoutedEventArgs) Handles _showAsyncButton.Click
Dim task = New WebClient().DownloadStringTaskAsync("http://www.microsoft.com")
'Dim task = New WebClient().DownloadStringTaskAsync("forcing error in async I/O")
task.ContinueWith(
Sub()
_resultField.Text = task.Result
'Throw New ApplicationException("forcing error in End method")
End Sub, Nothing, Nothing, TaskScheduler.FromCurrentSynchronizationContext
).ContinueWith(
Sub(a)
Select Case True
Case TypeOf (a.Exception.GetBaseException) Is WebException AndAlso CType(a.Exception.GetBaseException, WebException).Status = WebExceptionStatus.NameResolutionFailure
'Handle expected error
Dispatcher.Invoke(Sub() MessageBox.Show("Cannot access web site. Please try again later"))
Case Else
'Rethrow unexpected error in global error handler
Dispatcher.BeginInvoke(Sub() ExceptionDispatchInfo.Capture(a.Exception).Throw())
'ExceptionDispatchInfo.Capture(aex).Throw() 'Does not work
End Select
End Sub, TaskContinuationOptions.OnlyOnFaulted)
结束子