我知道这与问题Background worker exception handling有点相似,但有点不同。
因此,基于我对backgroundworkers的理解,当dowork()方法发生异常时,异常将传递给RunWorkerCompleted(对象发送者,RunWorkerCompletedEventArgs e)中的e.Error
。
我的问题有几个部分。
1。)是否会在发生异常的行之后停止执行所有其他代码,然后传递给RunWorkerCompleted
?在DoWork()
中使用try / catch来确保这种行为是必要/最佳做法吗?
2。)从DoWork()
或RunWorkerCompleted()
方法内部投掷时,也会抛出异常。
例如:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
//Should I be putting code in this as well as getting the exception in `RunWorkerCompleted()`?
//Or is the already how the background worker works already with out me needing to explicitly put the try/catch?
}
catch (Exception ex)
{
throw ex; //is this throwing to the 'RunWorkerCompleted()` or outside the thread to error handling on in the thread where RunWorkerAsync() was called?
}
}
private void backgroundowrker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null
{
throw e.Error; //This throws it back to the thread that called `RunWorkerAsync()` right?
}
}
答案 0 :(得分:1)
DoWork
方法中的任何代码都将无法访问代码,因此无法运行,Visual Studio实际上会警告您。通常使用异常作为流量控制是不赞成的 - 相反,我会使用包含错误字段的返回类型,因此您可以显式处理它,但这实际上取决于方案。RunWorkerCompleted
将在发起的线程上运行
异步方法调用。也就是说,无论哪个线程调用RunWorkerAsync
将是引发例外的那个我只想说我多年来没有使用过后台工作者 - .NET / C#中较新的异步功能使用起来更简洁。