【问题标题】:get filesystemwatcher events to occur on main UI thread获取在主 UI 线程上发生的 filesystemwatcher 事件
【发布时间】:2014-03-17 20:54:56
【问题描述】:

我可以让文件系统观察器事件在主 UI 线程上发生吗?目前文件更改是在它们自己的线程上触发的。

【问题讨论】:

  • WPF 还是 WinForms? WinForms 使用Control.Invoke(),WPF 使用您的事件处理程序中的Dispatcher.BeginInvoke() 将事件传递给您的 UI 线程。
  • winforms - 我的意思是更改事件 - 而不是我如何更新 GUI
  • 您不必更新 GUI,但控件知道它们在哪个线程上,这将获得一些代码在该线程上执行。你做什么取决于你。
  • @steve 你是对的。您要添加为答案以便我接受吗?
  • 听从 Hans Passant 的回答 - 我不知道这个解决方案。

标签: c# winforms filesystemwatcher


【解决方案1】:

只需将FileSystemWatcher.SynchronizingObject 属性设置为表单实例。与调用 BeginInvoke() 相同,但会自动为您完成。样板代码:

public Form1() {
    InitializeComponent();
    fileSystemWatcher1.SynchronizingObject = this;
}

【讨论】:

  • 它是单行的,很难看出你的问题。
  • 谢谢汉斯——我想很多人都会从你的智慧中受益
  • 如果在设计器中添加 FileSystemWatcher,SynchronizingObject 会在文件的代码中自动设置。
【解决方案2】:
this.BeginInvoke((MethodInvoker)(() => SomeMethod())); // Check files in the Main thread otherwise threading issues occur 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    相关资源
    最近更新 更多