2012-05-24 43 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

謝謝............... –