【问题标题】:thread and event [duplicate]线程和事件[重复]
【发布时间】:2012-05-24 08:39:01
【问题描述】:

可能重复:
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 的 ReiseEventOnUnitRead 方法。

在行中lstMetricUnit.ItemsSource = null;抛出异常 - “调用线程无法访问此对象,因为另一个线程拥有它。” 为什么?

【问题讨论】:

  • 这已被多次询问和回答。这是List

标签: c# .net wpf multithreading events


【解决方案1】:

您不能从不是 GUI 线程的另一个线程更改 GUI 项目,

如果您使用 WinForms,请使用 Invoke 和 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,请使用 Dispatcher。

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

【讨论】:

  • 谢谢......
【解决方案2】:

您应该使用调度程序。 示例:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多