我有以下代码,它创建一个临时文件夹并使用 FileSystemWatcher 轮询添加到 Location 属性文件夹中的文件,并将它们添加到列表中:Scratchdisk.cs on Pastebin .这个想法是创建一个 Scratchdisk 对象,并让 FFmpeg 将视频帧提取到其中,FileSystemWatcher 在 FFmpeg 创建这些文件时构建这些文件的列表,并将该列表显示为我的 UI 绑定(bind)到的 DependencyObject。
我像这样绑定(bind)到 Scratchdisk 对象:
<ItemsControl ItemsSource="{Binding Source=ThumbnailScratchdisk, Path=FileList}">
...
</ItemsControl>
虽然在实际创建对象时,我得到以下异常:
A first chance exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll
Additional information: The calling thread cannot access this object because a different thread owns it.
第 28 行 get { return (List<string>)GetValue(FileListProperty); }
我想我需要一个 Dispatcher.Invoke 某处,但我不知道在哪里,我不知道第二个线程是在哪里创建的。我假设它与 FileSystemWatcher 写入文件列表有关。
有什么帮助吗?
谢谢!
最佳答案
我的访问方式是这样的。它获取 UI 线程的 Dispatcher
System.Windows.Application.Current.Dispatcher.Invoke(
(Action)(() =>
{
//Access the UI from here
}));
在我所拥有的和您在评论中列出的之间,这里要注意的主要事情是,无论您是在后台代码、 View 模型、服务类中,还是在任何地方,我的都可以工作。并非所有项目都有 Dispatcher
,因此 this.Dispatcher
并不总是有效。
关于c# - WPF DependencyObject 调用线程异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27091348/