我的控制台应用程序使用 System.ComponentModel.BackgroundWorker
进行线程处理:
System.ComponentModel.BackgroundWorker backgroundWorker = new System.ComponentModel.BackgroundWorker();
backgroundWorker.DoWork += (sender, e) =>
ReportStatus(worker, status, result, e);
backgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
backgroundWorker.RunWorkerAsync(worker);
如您所见,我在 RunWorkerAsync 中传递“worker”作为参数。
我想要实现的是,如果 ReportStatus 方法内出现异常,我需要相同的“worker”对象,以便我可以执行某些操作(调用服务来通知 worker 异常)
private void ReportStatus(Worker worker, Status status, WorkResult result,System.ComponentModel.DoWorkEventArgs arg)
{
var proxy = new PreparationServiceProxy(new NetTcpBinding(), new EndpointAddress(PreparationEngineState.ServiceAddress));
try
{
proxy.ReportStatus(worker, status, result);
proxy.Close();
}
catch (Exception)
{
arg.Result = worker;
proxy.Abort();
throw;
}
}
在我的异常 block 中(我不确定这是否是正确的方法!)我将工作人员分配给结果,以便在执行 RunWorkerCompleted 方法(backgroundWorker1_RunWorkerCompleted)时可以返回相同的工作人员:
private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
Worker worker = e.Result as Worker; // At this point I get an exception!
}
}
最佳答案
这是因为你重新抛出了异常。 BackgroundWorker
将其视为 DoWork
处理程序未处理的异常,并在获取 Result
值时将其重新抛出回另一个线程。
如果您不希望它这样做,请在 DoWork
处理程序中删除 catch 中的 throw
。
如果您将工作对象传递到 BackgroundWorker
中,为什么不使用您在包装对 Result
的调用的异常处理程序中或在测试 Error
的 block ?例如:
if (e.Error != null)
{
worker.DoSomething(); // no access of Result
}
关于c# - 在发生异常时将自定义对象传递给 RunWorkerCompleted 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12395782/