我在代码中添加了一个事件处理程序,它中断了对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
}
}发布于 2010-05-31 10:17:56
我最终用ObservableCollection替换了CollectionViewSource,一切工作正常。
发布于 2010-05-31 04:46:11
这不是关于“线程锁定”,而是关于一个众所周知的问题,即图形用户界面(无论是WPF还是WinForms)不是线程安全的,并且在调试版本中有对跨线程调用的主动检查。
因此,您已经知道解决方案:在主线程上创建SystemHTA对象。你的问题可能会转移到从DeviceMgr加载它,你可能不得不在这里使用Control.Dispatcher.Invoke()。
https://stackoverflow.com/questions/2940175
复制相似问题