线程锁定CollectionViewSource

时间:2010-05-30 20:26:34

标签: c# wpf c#-4.0

我为我的代码添加了一个事件处理程序,它破坏了对SystemHTA类中CollectionViewSources的所有访问,说“调用线程无法访问此对象,因为另一个线程拥有它”。我的班级在“this.systemHTA = new SystemHTA();”时正在工作被放置在DeviceManager_StateChanged()函数之外。

    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
        }
    }

2 个答案:

答案 0 :(得分:1)

这不是关于'线程锁定',而是关于GUI(WPF或WinForms)不是线程安全的众所周知的问题,并且在Debug构建中有主动检查跨线程调用。

所以你已经知道了解决方案:在主线程上创建SystemHTA对象。您的问题可能会转移到从DeviceMgr中加载它,您可能必须在此处使用Control.Dispatcher.Invoke()

答案 1 :(得分:1)

我最终用一个ObservableCollection替换了CollectionViewSource,一切正常。