c# - WPF DependencyObject 调用线程异常

标签 c# wpf multithreading filesystemwatcher invalidoperationexception

我有以下代码,它创建一个临时文件夹并使用 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/

相关文章:

c# - 在 System.Drawing.Color 中使用十六进制颜色代码

c# - 我无法在我的项目中使用我已经导入的库作为引用

Android listview空指针异常?

Java 8 可能的双 Lambda 表达式

c# - 如何将许多不同的线程放入 wait() 并能够使用 signalAll() 唤醒它们?

c# - input submit 有两种类型的值

C# WPF 移动窗口

c# - WPF DragDropEffects 在 Drop 事件中未正确设置

c# - 如何在 slider 上画线或其他东西?

c# - 从 HttpResponseMessage.Content 读取流式内容