This question is not about the dodgy way events fire, because I don’t mind that.
I am doing something wrong here but once again I am code blind or missing a piece of the puzzle.
Setting: On Windows forms, one can implement a FileSystemWatcher in two ways.
Implementation 1: Dropping a
FilesystemWatcher
from the toolbox onto the Form.
I have these settings under properties:
Name.................FileSystemWatcher1
GenerateMembers......True
Modifiers ...........Private
EnableRaisingEvents..True
Filter ..............*.*
IncludeSubFolders....True
NotifyFiler..........LastWrite
Path ............... C:\somdir
Under event properties
Changed FileSystemWatcher1_created
With debugger I can see the
SynchonizingObject = this
.
My partial form class holds the
FileSystemwatcher1_created
implementation
Implementation 2: By coding the FileSystemwatcher
I put this code in my buttonclicked method from one of the form buttons. (Or even if I put it in the constructor of the form)
{
FileSystemWatcher fs = new FileSystemWatcher(@"C:\somedir");
fs.NotifyFilter = NotifyFilters.LastWrite;
fs.Filter = "*.*";
fs.IncludeSubdirectories = true;
fs.SynchronizingObject = this;
fs.Changed += new FileSystemEventHandler(OnChanged);
fs.EnableRaisingEvents = true;
}
And a OnChanged implementation:
private void OnChanged(object source, FileSystemEventArgs args)
{
int a = 5;
}
Now for the difference:
1. When I copy a file to the watched folder both implementations fire an event and execute the code I want to execute as a result. So far so good.
2. But, in real life these file are created by 3rd party system which keeps on writing to these files. In this situation in Implementation 1. I get what I want. Event is fired and handler executed. In Implementation 2. Nothing happens until I close the 3rd party app, which never happens is real life.
Why this difference?
I tried with changing
synchonizeobject = this
or
= null
.
What I am doing wrong here?
Background info which you can skip if you want.
I have to migrate the app from FORMS to WPF. So I have to implement on code. I noticed the difference in behaviour so I made this test set to investigate my mistake. First I thought that it had to do with the missing ISynchronizeInvoke Interface in WPF.
But since I can reproduce the same behaviour in my Forms test set It must be something else that I am doing wrong.