从RunWorkerCompleted处理不同的.Net异常(不参考DoWork异常)

时间:2011-01-17 19:37:47

标签: .net exception exception-handling backgroundworker

我正在处理处理AppDomain.CurrentDomain.UnhandledExceptionApplication.ThreadException的例程。我只是从异常中抓取MessageStackTrace并立即记录。

(旁注,StackTrace看起来格式很好,在IDE中使用换行符,但是当ToString被调用时,它会丢失格式化,我无法弄清楚如何修复这一点。)

所以我有以下代码来测试这个:

Private Sub frmMain_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
    'if you don't remove the handlers you'll leak memory
    RemoveHandler AppDomain.CurrentDomain.UnhandledException, AddressOf ErrorProcesser.UnhandledException
    RemoveHandler Application.ThreadException, AddressOf ErrorProcesser.UnhandledException
End Sub

Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf ErrorProcesser.UnhandledException
    AddHandler Application.ThreadException, AddressOf ErrorProcesser.UnhandledException
End Sub

Private Sub btnException_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnException.Click
    Throw New Exception("Test Exception - Main Thread", New Exception("Inner Exception Data - Main Thread"))
End Sub

Private Sub btnThreadingException_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThreadingException.Click
    BackgroundWorker1.RunWorkerAsync()
End Sub

Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    'this will be in e.Errors in the RunWorkerCompleted
    Throw New Exception("Test Exception - Spawned Thread", New Exception("Inner Exception Data - Spawned Thread"))
End Sub

Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
    Throw New Exception("Test Exception - Returned Thread", New Exception("Inner Exception Data - Returned Thread"))
End Sub

现在,当我查看我的日志时,我看到一个条目为“Test Exception - Main Thread”,其中填充了StackTrace,另一个条目为“Inner Exception Data - Returned Thread”,其中StackTrace为NULL 。我期待的是“测试异常 - 主线程”的一个条目,其中填充了StackTrace,另一个条目为“测试异常 - 返回的线程”,其中填充了StackTrace

为什么Exception引发的RunWorkerCompleted仅在第一种情况下注册为InnerException而不是Exception?我已经验证了完全相同的代码正在处理这两个调用。

0 个答案:

没有答案