且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

BackgroundWorker 线程必须是 STA

更新时间:2023-11-14 15:37:04

您不应尝试从后台线程与任何 UI 组件进行交互.

You should not try to interact with any UI components from a background thread.

一种方法是在 doWork 方法中捕获异常并将其分配给后台工作器的 result 属性,然后检查该结果是否为异常类型,或者如果您不将结果用于其他任何事情,则检查该结果是否为空.然后在 backgroundWorker_completed 事件中检查它.

One way could be to catch the exception in your doWork method and assign it to the backgroundworker's result property and then check if that result is a type of exception or not null if you are not using the result for anything else. then check for it in the backgroundWorker_completed event.

BackgroundWorker_DoWork(sender, )
{
    try
    {
       // do work        
    }
    catch (Exception ex)
    {
         BackgroundWorker w = sender as BackgroundWorker;
         if (w != null)
             w.Result = ex;
    }
}

然后

BackgroundWorker_Completed()
{
    if (s.Result != null && e.Result is Exception)
    {
       Exception ex = e.Result as Exception;
       // do something with ex
    }
}