WPF DependencyObject调用线程异常 [英] WPF DependencyObject calling thread exception
问题描述
我有以下代码,该代码创建一个临时文件夹并使用FileSystemWatcher轮询添加到Location属性上的文件夹的文件,并将它们添加到列表中:
I have the following code which creates a temporary folder and uses a FileSystemWatcher to poll for files added to the folder on the Location property, and add them to a list: Scratchdisk.cs on Pastebin. The idea is to create a Scratchdisk object, and have FFmpeg extract video frames into it, the FileSystemWatcher builds a list of these files as FFmpeg creates them, and the list is presented as a DependencyObject that my UI binds to.
我像这样绑定到Scratchdisk对象:
I'm binding to the Scratchdisk object like so:
<ItemsControl ItemsSource="{Binding Source=ThumbnailScratchdisk, Path=FileList}">
...
</ItemsControl>
在实际创建对象时,出现以下异常:
On actually creating the object though, I get the following exception:
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写入文件列表有关.
I think I need a Dispatcher.Invoke somewhere but I have no idea where, I don't know where the second thread is being created. I'm assuming it has something to do with the FileSystemWatcher writing to the file list.
有帮助吗?
谢谢!
推荐答案
我访问它的方式是这样的.它获取UI线程的分派器
The way I access it is like this. It gets the UI Thread's Dispatcher
System.Windows.Application.Current.Dispatcher.Invoke(
(Action)(() =>
{
//Access the UI from here
}));
在这里我要注释的内容之间要注意的主要事情是,无论您在后面的代码,视图模型,服务类中,无论我在哪里,我的代码都将起作用.并非所有项目上都带有Dispatcher
,因此this.Dispatcher
并不总是有效.
The main thing to note here between what I have and what you have listed in the comments is that mine will work regardless if you're in the behind code, the view model, a service class, wherever. Not all items have a Dispatcher
on them so this.Dispatcher
doesn't always work.
这篇关于WPF DependencyObject调用线程异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!