我已经充分使用BackgroundWorker了一年多,并且非常了解它。
就在最近,我RunWorkerCompleted根本没赶上e.Error我Throw New Exception("Test")在DoWork. 但是引发了未处理的异常。赶上DoWork不是最好的做法,因此e.Error没有意义。
当我尝试使用 new 创建 newForm时,BackgroundWorker已成功处理。我的复杂中应该有问题。e.ErrorRunWorkerCompletedBackgroundWorker
经过几天的谷歌搜索和调试,尝试了一个错误。我在我的RunWorkerCompleted:
- 首先检查
e.Error,然后检查e.Cancelled,最后检查e.Result
- 不要得到
e.Resultif e.Cancelled = True。
- 不要得到
e.Resultif e.Erroris not null(or Nothing) **
**这是我想念的地方。如果您尝试使用e.Resultif e.Erroris not null(or Nothing),则会抛出 Unhandled Exception。
更新:
在e.Result获取属性 .NET 中设计它首先检查e.Error,如果有错误,那么他们将重新从 .NET 中抛出相同的异常DoWork。这就是为什么我们得到 Unhandled 异常RunWorkerCompleted但实际上异常来自DoWork.
这是最好的做法RunWorkerCompleted:
If e.Error IsNot Nothing Then
' Handle the error here
Else
If e.Cancelled Then
' Tell user the process canceled here
Else
' Tell user the process completed
' and you can use e.Result only here.
End If
End If
如果您想要一个可供所有 DoWork、ProgressChanged 和 RunWorkerCompleted 访问的对象,请像这样使用:
Dim ThreadInfos as Dictionary(Of BackgroundWorker, YourObjectOrStruct)
您可以轻松访问ThreadInfos(sender).Field任何您想要的地方。