6

Can i get filesystemwatcher events to occur on the main UI thread ?. Currently file changes are fired off on their own threads.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
user1438082
  • 2,740
  • 10
  • 48
  • 82
  • 1
    WPF or WinForms? WinForms use `Control.Invoke()`, WPF use `Dispatcher.BeginInvoke()` from your event handler to pass the event off to your UI thread. – Steve Mar 17 '14 at 20:58
  • winforms - what i mean is a change event - not how do i update the GUI – user1438082 Mar 17 '14 at 20:59
  • 1
    You don't have to update the GUI, but the controls know what thread they're on, and this will get some code to execute on that thread. What you do is up to you. – Steve Mar 17 '14 at 21:00
  • @steve you are correct. Do you want to add as an answer so i can accept? – user1438082 Mar 17 '14 at 22:28
  • 1
    Go with Hans Passant's answer - I was unaware of this solution. – Steve Mar 19 '14 at 19:01

2 Answers2

16

Simply set the FileSystemWatcher.SynchronizingObject property to the form instance. Same thing as calling BeginInvoke() but done automatically for you. Boilerplate code:

public Form1() {
    InitializeComponent();
    fileSystemWatcher1.SynchronizingObject = this;
}
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
2
this.BeginInvoke((MethodInvoker)(() => SomeMethod())); // Check files in the Main thread otherwise threading issues occur 
user1438082
  • 2,740
  • 10
  • 48
  • 82