4
votes

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

2
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
winforms - what i mean is a change event - not how do i update the GUIuser1438082
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
@steve you are correct. Do you want to add as an answer so i can accept?user1438082
Go with Hans Passant's answer - I was unaware of this solution.Steve

2 Answers

13
votes

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;
}
2
votes
this.BeginInvoke((MethodInvoker)(() => SomeMethod())); // Check files in the Main thread otherwise threading issues occur