c# - 如何处理从BackgroundWorker的DoWork处理程序抛出的异常?

标签 c# exception backgroundworker

我想处理 RunWorkerCompleted 处理程序中的 DoWork 处理程序内部发生的异常,但是当代码在调试器下运行时,我首先收到另一个异常“异常未处理”通过用户代码”。

这是我正在使用的代码的简短示例:

BackgroundWorker _worker;
public void Test()
{
    _worker = new BackgroundWorker();
    _worker.WorkerReportsProgress = false;
    _worker.WorkerSupportsCancellation = false;

    _worker.DoWork += new DoWorkEventHandler(bw_DoWork);
    _worker.RunWorkerCompleted += new
        RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
    _worker.RunWorkerAsync();
}

private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    e.Result = ActuallWorkHere();
}

private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    var t = e.Error;
}

private IEnumerable<string> ActuallWorkHere()
{
    throw new Exception("test");
    // "Exeption was unhandled by user code" if called
    string[] res = { "test" };
    return res;
}

我做错了什么?

最佳答案

您并没有真正做错任何事情,这就是 Visual Studio 在调试器中运行代码时对未处理错误所做的操作:

来自BackgroundWorker.DoWork Event在 MSDN 上:

If you are running under the Visual Studio debugger, the debugger will break at the point in the DoWork event handler where the unhandled exception was raised.

尝试运行你编译的程序,你不会看到这个。

请注意,您可以在 DoWork 和 RunWorkerCompletedEventArgs.Error 中处理此异常。 RunWorkerCompleted 处理程序中的属性仍将存储错误的详细信息。

关于c# - 如何处理从BackgroundWorker的DoWork处理程序抛出的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10453121/

相关文章:

c# - 在 C# 中,将大文件加载到 winform richtextbox

c# - 我如何将 "Thread.Join"设置为 BackgroundWorker?

c# - 如何在运行时制作exe maker

ios - UIPickerView iOS7.1 中的未定义键 NSException

c# - JSON.NET。从其子项导航到 JArray 对象

database - 如何检查值是否在数据库中而不在 Zend 中抛出异常?

python - 无法捕获 SystemExit 异常 Python

c# - 如何记录 BackgroundWorker.RunWorkerAsync(Object) 的参数?

c# - 在 C# 中读取 excel (.xlsx) 文件

c# - C#结构数组的内存布局