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??
lockdoes 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
FileSystemWatcherraises itsChangedevent on a threadpool thread.If you want to have
DispatchResultoccur on a single thread, you’ll need to use some form ofSynchronizationContextto push the result back onto that thread. In a UI application, this is typically done viaControl.InvokeorDispatcher.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.