tags:

views:

60

answers:

2

I added an event handler to my code and it broke all access to the CollectionViewSources in the SystemHTA class saying "The calling thread cannot access this object because a different thread owns it". My class was working when "this.systemHTA = new SystemHTA();" was placed outside of the DeviceManager_StateChanged() function.

    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  A: 

This is not about 'Thread Locking' but about the well known problem that a GUI (either WPF or WinForms) is not threadsafe and in a Debug build there is active checking for cross-thread calls.

So you already know the solution: create the SystemHTA object on the main thread. Your problem may shift to loading it from the DeviceMgr stuff, you may have to use Control.Dispatcher.Invoke() here.

Henk Holterman
I'm still completely baffled as how to do that.
Robert
I can imagine that (-: , here is a slightly easier link, but keep googling: http://msdn.microsoft.com/en-us/magazine/cc163328.aspx
Henk Holterman
+1  A: 

I ended up replacing the CollectionViewSource with an ObservableCollection and everything works fine.

Robert