2010-05-30 134 views
1

我添加了一個事件處理程序,我的代碼,它打破了所有訪問在SystemHTA班說:「因爲不同的線程擁有它調用線程不能訪問該對象的」 CollectionViewSources。當我的課程「this.systemHTA = new SystemHTA();」被放置在DeviceManager_StateChanged()函數的外部。線程鎖定CollectionViewSource

public partial class MainWindow : Window 
    { 
     private DeviceManager DeviceManager = DeviceManager.Instance; 
     public SystemHTA systemHTA; 

     public MainWindow() 
     { 
      InitializeComponent(); 
     } 

     private void Window_Loaded(object sender, RoutedEventArgs e) 
     { 
      DeviceManager.StateChanged += new EventHandler<DeviceManagerStateChangedEventArgs>(DeviceManager_StateChanged); 
      DeviceManager.Initialize(); 
     } 

     void DeviceManager_StateChanged(object sender, DeviceManagerStateChangedEventArgs e) 
     { 
      if (e.State == DeviceManagerState.Operational) 
      { 
       this.systemHTA = new SystemHTA(); 
      } 
     } 

     private void button1_Click(object sender, RoutedEventArgs e) 
     { 
      this.systemHTA.GetViewSourceTest(); 
     } 
    } 


    public class SystemHTA 
    { 
     private CollectionViewSource _deviceTestSource; 

     public SystemHTA() 
     { 
      _deviceTestSource = new CollectionViewSource(); 
      _deviceTestSource.Source = CreateLoadData<HWController>.ControllerCollection; 
     } 

     public void GetViewSourceTest() 
     { 
      ListCollectionView view = (ListCollectionView)_deviceTestSource.View; //This creates an error saying a thread already owns _deviceTestSource 
     } 
    } 

回答

1

我最終用ObservableCollection替換CollectionViewSource,一切正常。

1

這不是關於「螺紋鎖固」,但有關公知的問題,即,GUI(或WPF或WinForms的)不是線程並在調試建立有用於跨線程調用活性檢查。

因此,您已經知道解決方案:在主線程上創建SystemHTA對象。你的問題可能會轉移到從DeviceMgr的東西加載它,你可能不得不在這裏使用Control.Dispatcher.Invoke()

+0

我仍然完全困惑如何做到這一點。 – Robert 2010-05-30 21:37:22

+0

我可以想象( - :,這裏是一個稍微簡單的鏈接,但請繼續搜索:http://msdn.microsoft.com/en-us/magazine/cc163328.aspx – 2010-05-30 22:00:01