多线程环境问题

本文关键字:问题 环境 多线程 | 更新日期: 2023-09-27 18:34:52

我有一个 WPF 控件,它正在我的应用程序的主线程中处理、呈现和显示。该控件将数千个数据点上载到名为"Layer"的对象中的视图中。以下是对象/类层次结构的粗略描述:

public class WPFControl{
   private List<Layer> myLayers;
   public List<Layer> MyLayers{
      get{ return myLayer;}
   }       
   ...
}
public class Layer{
   private List<DataPoint> myDataPoints;
   public List<DataPoint> MyDataPoints{
        get{ return myDataPoints;}
   }
   ...
}
public class DataPoint{
   ....
}

由于此"层"对象的创建过程需要一些时间,因为它必须读取和上传数千个数据点,因此我正在不同的线程中创建该层对象。这很好用,并且很好地返回了 Layer 对象。问题是当我尝试将其添加到WPF控件以如下所示显示时:

myWpfControl.MyLayers.Add(layerCreatedInOtherThread);

WPF 控件触发此错误:

The calling thread cannot access this object because a different thread owns it

我想,好吧,然后我可以像这样使用调度程序:

myWpfControl.Dispatcher.Invoke((Action)
 (()=>{                                   
    myWpfControl.MyLayers.Add(layerCreatedInOtherThread);
 })
 );

但是我不断收到同样的错误。任何想法如何解决这个问题?

多线程环境问题

使用BackgroundWorker,您可以在另一个线程上运行任务,然后在任务完成后访问 UI 线程的结果。

private System.ComponentModel.BackgroundWorker bgWorker;
bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
 //Start the work
 bgWorker.RunWorkerAsync(null) //you can send an argument instead of null

做工作

    private void backgroundWorker1_DoWork(object sender, 
        DoWorkEventArgs e)
    {   
        // Get the BackgroundWorker that raised this event.
        BackgroundWorker worker = sender as BackgroundWorker;
        // Assign the result of the computation 
        // to the Result property of the DoWorkEventArgs 
        // object. This is will be available to the  
        // RunWorkerCompleted eventhandler.
        e.Result = CreateLayerInOtherThread(); //if you sent an arg instead of null it as availalbe in e.Argument and can be cast from object.
    }

完成后获取结果。 这将在 UI 线程上运行,以便您可以更新它。

    private void bgWorker_RunWorkerCompleted(
        object sender, RunWorkerCompletedEventArgs e)
    {
        // First, handle the case where an exception was thrown. 
        if (e.Error != null)
        {
            MessageBox.Show(e.Error.Message);
        }
        else if (e.Cancelled)
        {
            // Next, handle the case where the user canceled  
            // the operation. 
            // Note that due to a race condition in  
            // the DoWork event handler, the Cancelled 
            // flag may not have been set, even though 
            // CancelAsync was called.

        }
        else
        {
            // Finally, handle the case where the operation  
            // succeeded.
            Layer myLayer = (Layer)e.Result;
            myWpfControl.MyLayers.Add(myLayer);
        }

    }