19

I want this work to be done in a different thread but do i have to create a thread or does it do all the work on different threads?

Like:

Thread fileThread = new Thread(() =>
{
    FileWatcher = new FileSystemWatcher();

    FileWatcher.Created += OnFileEvent;
    FileWatcher.Deleted += OnFileEvent;
    FileWatcher.Renamed += OnRenameEvent;
    FileWatcher.EnableRaisingEvents = true;
});

fileThread.Start();
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
syncis
  • 1,395
  • 4
  • 25
  • 43

1 Answers1

25

You don't have to create a thread. The events will be called on a separate thread automatically.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 1
    ok perfekt, i got another question: Once i stop the watcher, i set enableraisingeevents = false, but when i want to start the watcher again , i dont know if i should just enableraisingevents=true or if i should create a new instance of the filesystemwatcher like the above code, what do you think? Thank you – syncis Jul 15 '12 at 14:42
  • 2
    @syncis: If you keep the instance, you can just turn it on again. – Guffa Jul 15 '12 at 14:54
  • 1
    Ok my concern was that i dont want it to do any work at some point and if its enableraisingevents = false , i thought it would do all the work but just not raise the events. – syncis Jul 15 '12 at 14:58
  • 1
    @syncis: If you are concerned about that, then you should create a new object instead. However, just turning off enableraisingevents will not stop it from listening for changes, you should call Dispose when you don't use it any more. – Guffa Jul 15 '12 at 15:16
  • 1
    How would the debugger handle that? – Daniel Möller Feb 20 '14 at 02:17
  • @Guffa Why do you think that turning off _EnableRaisingEvents_ will not stop it from listening? What I can see [in the source code](https://referencesource.microsoft.com/#System/services/io/system/io/FileSystemWatcher.cs,e5f51c0ec64db0d4) is that it will. – Ahmad Ibrahim Jun 11 '17 at 02:28