使用后台辅助角色进行异常处理

本文关键字:异常处理 角色 后台 | 更新日期: 2023-09-27 18:37:28

我知道这有点类似于后台工作者异常处理的问题,但它有点不同。

因此,根据我对 backgroundworker 的理解,当 dowork() 方法中发生异常时,异常将传递给 RunWorkerCompleted(对象发送者,RunWorkerCompleteEventArgs 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?
    }
}

使用后台辅助角色进行异常处理

  1. 引发异常后,DoWork方法中的任何代码都将是无法访问的代码,因此它不会运行,Visual Studio 实际上会警告您这一点。一般来说,使用异常作为流控制是不受欢迎的 - 相反,我会使用包含错误字段的返回类型,以便您可以显式处理它,但这实际上取决于场景。
  2. RunWorkerCompleted将在启动异步方法调用。也就是说,无论哪个线程调用RunWorkerAsync将是引发异常的那个

我只是要警告说我已经很多年没有使用后台工作线程了 - .NET/C# 中较新的异步功能使用起来更干净。