【发布时间】:2014-11-23 16:33:44
【问题描述】:
我有以下代码创建一个临时文件夹并使用 FileSystemWatcher 轮询添加到 Location 属性上的文件夹中的文件,并将它们添加到列表中:Scratchdisk.cs on Pastebin。这个想法是创建一个 Scratchdisk 对象,并让 FFmpeg 将视频帧提取到其中,当 FFmpeg 创建这些文件时,FileSystemWatcher 会构建这些文件的列表,并且该列表显示为我的 UI 绑定到的 DependencyObject。
我正在像这样绑定到 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.
在线28get { return (List<string>)GetValue(FileListProperty); }
我想我需要一个 Dispatcher.Invoke,但我不知道在哪里,我不知道第二个线程是在哪里创建的。我假设它与 FileSystemWatcher 写入文件列表有关。
有什么帮助吗?
谢谢!
【问题讨论】:
-
FileSystemWatcher从不同的线程引发事件。尝试 changindWatcher_Created做类似this.Dispatcher.Invoke(new Action(() => AddFileReference(e.FullPath)))的事情。 -
@dkozl 这成功了,谢谢!
标签: c# wpf multithreading filesystemwatcher invalidoperationexception