I have the following code:
private void WatchFileForChanges()
{
if (fileInfo.Directory != null)
{
_watcher = new FileSystemWatcher(fileInfo.Directory.FullName, fileInfo.Name);
_watcher.NotifyFilter = NotifyFilters.LastWrite;
_watcher.Changed += OnFinalBuilderStatusChanged;
_watcher.EnableRaisingEvents = true;
}
}
private void OnChanged(object source, FileSystemEventArgs e)
{
lock (this)
{
// here i see 2 different threads coexist
// even there is a lock!!
DispatchResult();
}
}
as can be sing in the comment, i am seeing to different threads co-exist in the OnChanged even there is a lock mechanism, how come??
lock
does not cause the thread being used to change. I merely prevents multiple threads from accessing the code within that block at the same time.
The reason you're getting multiple threads here is that FileSystemWatcher
raises its Changed
event on a threadpool thread.
If you want to have DispatchResult
occur on a single thread, you'll need to use some form of SynchronizationContext
to push the result back onto that thread. In a UI application, this is typically done via Control.Invoke
or Dispatcher.Invoke
, for example.
On a side note, it's a good idea to avoid using lock(this)
, and instead make a private object that's used just for your locking. Otherwise, another object could lock on your same instance and cause all sorts of issues.