0

我真的在 Stackoverflow 上阅读了所有其他类似的主题。没有什么对我有用...我抛出“异常”类型的异常,但我无法处理异常。

我已经在 DoWork Progress 的 CompletedEvent 中尝试过(使用 try/catch,witch e.error ....)

void bgGetResponse_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Error != null)
    {
        MessageBox.Show(e.Error.Message);
        ConvertByte(myFile);
        myFile= null;
    }
}

void bgGetResponse_DoWork(object sender, DoWorkEventArgs e)
{
    byte[] test= new byte[] { 1, 1, 0, 1, 1};
    //Here the error occured (just with  throw new Exception("error"))
    //The method only throws an exception (for test purposes)
    testResponse= _configManager.GetResponse(test, 0);
}

GetResponse(...)
{

   throw new Exception("..!");

}

有任何想法吗?

感谢您的努力

4

3 回答 3

2

我通常只是在工作方法中捕获它并将结果设置为它。

private void BGW_DoWork(object sender, DoWorkEventArgs e)
{
    ...
}
catch (Exception ex)
{
    e.Result = ex;
}

然后查看 Completed 事件,

私人无效BGW_RunWorkerCompleted(对象发送者,RunWorkerCompletedEventArgs e){ this.Cursor = Cursors.Default;

try
{
    Exception ex = e.Result as Exception;
    if (null != ex)
        throw ex;

...

于 2012-08-15T14:01:42.970 回答
1

如果通过“无法处理”您的意思是 can't use 的异常catch,那是真的。您只需使用 Error 属性。您可以在 Completed 事件处理程序中“抛出”它;但是你的堆栈框架会有所不同。

例如:

try
{
    if(e.Error != null) throw(e.Error)
    // handle success case
}
catch(MyException exception)
{
    // handle specific error.
}
于 2012-08-15T13:49:10.220 回答
1

BackgroundWorkers DoWork 函数中发生的任何未处理的异常都将导致工作人员触发 RunWorkerCompleted,其中事件参数将包含错误。

于 2012-08-15T14:00:56.680 回答