2012-05-24 46 views
0

可能重复:
Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on
WPF access GUI from other thread线程和事件

美好的一天, 我写的类

public class Metric1 
{ 
     public event MetricUnitEventHandler OnUnitRead; 


     public void ReiseEventOnUnitRead(string MetricUnitKey) 
     { 
      if (OnUnitRead!=null) 
      OnUnitRead(this,new MetricUnitEventArgs(MetricUnitKey)); 
     } 
..... 
}  

Metric1 m1 = new Metric1(); 
m1.OnUnitRead += new MetricUnitEventHandler(m1_OnUnitRead); 

void m1_OnUnitRead(object sender, MetricUnitEventArgs e) 
{ 
     MetricUnits.Add(((Metric1)sender)); 
     lstMetricUnit.ItemsSource = null; 
     lstMetricUnit.ItemsSource = MetricUnits;  
} 

然后,我开始新的线程,每分钟话费m1的ReiseEven tOnUnitRead方法。

在第lstMetricUnit.ItemsSource = null行;抛出excepition - “调用线程无法访问此对象,因为不同的线程拥有它。”为什么?

+4

这已被问及多次回答。这里是[列表](http://stackoverflow.com/search?q=wpf+%22other+thread%22) –

回答

1

您应该使用分派器。 实施例:

Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => { 
     lstMetricUnit.ItemsSource = null; 
     lstMetricUnit.ItemsSource = MetricUnits;  
}))); 

在WPF和表格 - >不能从不同的线程修改UI控件。

3

您不能从另一个线程不是GUI线程改变用户界面项目,

如果您正在使用的WinForms工作使用调用和InvokeRequired。

if (lstMetricUnit.InvokeRequired) 
{   
    // Execute the specified delegate on the thread that owns 
    // 'lstMetricUnit' control's underlying window handle. 
    lstMetricUnit.Invoke(lstMetricUnit.myDelegate);   
} 
else 
{ 
    lstMetricUnit.ItemsSource = null; 
    lstMetricUnit.ItemsSource = MetricUnits; 
} 

如果您正在使用WPF使用分派器。

lstMetricUnit.Dispatcher.Invoke(
      System.Windows.Threading.DispatcherPriority.Normal, 
      new Action(
      delegate() 
      { 
       lstMetricUnit.ItemsSource = null; 
       lstMetricUnit.ItemsSource = MetricUnits; 
      } 
     )); 
+0

谢谢............... –