0

重複の可能性:クロススレッド操作が無効です:他のスレッドからのWPFアクセスGUI
で作成されたスレッド以外のスレッドからアクセスされたコントロール

良い一日、私はクラスを書きます

 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で; 例外をスローします- 「別のスレッドがオブジェクトを所有しているため、呼び出し元のスレッドはこのオブジェクトにアクセスできません。」 なんで?

4

2 に答える 2

3

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;   
            }
        ));
于 2012-05-24T08:43:17.250 に答える
1

Dispatcherを使用する必要があります。例:

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

WPFおよびフォーム->では、異なるスレッドからUIコントロールを変更することはできません。

于 2012-05-24T08:45:27.863 に答える