为了提高健壮性,我想添加一个处理程序来处理TaskScheduler.UnobservedTaskException。
该处理程序将记录异常信息并通知用户关闭应用程序。
以下是实现的示例,你觉得它合理吗? 在这个处理程序中,在WPF中显示一个MessageBox或Windows是否可行?或者说这是一个坏主意,因为我们正在运行未观察到的任务的终结器?
以下是实现的示例,你觉得它合理吗? 在这个处理程序中,在WPF中显示一个MessageBox或Windows是否可行?或者说这是一个坏主意,因为我们正在运行未观察到的任务的终结器?
Private Sub TaskSheduler_UnobservedTaskException(sender As Object, e As UnobservedTaskExceptionEventArgs)
Static _wasUserInformed As Boolean = False
e.SetObserved()
'Trace all Exceptions
e.Exception.Flatten.Handle(Function(ex As Exception)
'TODO trace and log Exception
Debug.Print("UnobservedTaskException: {0}", ex.Message)
Return True
End Function)
If Not _wasUserInformed Then
'Show root Exception
_wasUserInformed = True
Application.Current.Dispatcher.BeginInvoke(Sub()
'MessageBox.Show(e.Exception.GetBaseException.Message)
Dim win As New UnexpectedExceptionWindow
win.UnexpectedException = e.Exception.GetBaseException
win.ShowDialog()
Application.Current.Dispatcher.BeginInvoke(Sub() Application.Current.Shutdown())
End Sub)
End If
结束子程序
[编辑] 我们的讨论得出以下解决方案。
Private Sub TaskScheduler_UnobservedTaskException(sender As Object, e As UnobservedTaskExceptionEventArgs
) Handles TaskScheduler.UnobservedTaskException
Static _wasUserInformed As Boolean = False
'Free the finalizer thread and execute on the UI thread to be able to inform user
Dispatcher.BeginInvoke(Sub() LogException(e.Exception))
e.SetObserved()
If Not _wasUserInformed Then
_wasUserInformed = True
'Show first error
Dispatcher.BeginInvoke(Sub()
NotifyUser(e.Exception)
Application.Current.Shutdown()
End Sub)
End If
End Sub