Can i get filesystemwatcher events to occur on the main UI thread ?. Currently file changes are fired off on their own threads.
Asked
Active
Viewed 4,422 times
6
-
1WPF 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
-
1You 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
-
1Go with Hans Passant's answer - I was unaware of this solution. – Steve Mar 19 '14 at 19:01
2 Answers
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
-
-
thanks Hans - i think alot of people will benefit from your wisdom – user1438082 Mar 19 '14 at 19:52
-
1If you add the FileSystemWatcher in the designer, the SynchronizingObject is set automatically in the code behind file. – Paul Williams May 02 '20 at 00:05
2
this.BeginInvoke((MethodInvoker)(() => SomeMethod())); // Check files in the Main thread otherwise threading issues occur

user1438082
- 2,740
- 10
- 48
- 82