Dear all;
I need to monitor a xml file so that I can update my data in
hashtable, but the problem is it will trigger more than one event for
a lastwrite action(I trigger this action by add something in the xml
file using notepad).
Here is my codes about using FilesystemWatcher
fileWatcher=new FileSystemWatcher();
fileWatcher.Path=System.Environment.CurrentDirecto ry;
fileWatcher.NotifyFilter=NotifyFilters.LastWrite;
fileWatcher.Filter="SACHandlers.xml";
fileWatcher.Changed+=new FileSystemEventHandler(OnChanged);
fileWatcher.IncludeSubdirectories=false;
fileWatcher.EnableRaisingEvents = true;
And here is the OnChanged code
Monitor.Enter(this);
//_reentryLock=true;
Hashtable _ht = null;
string msg="";
DateTime _dt= DateTime.Now;
ReportMessage(_lastTriggerTime.ToString());
log.Info("lasttriggertime:" + _lastTriggerTime.ToString());
ReportMessage(_dt.ToString());
log.Info("dt time:" + _dt.ToString());
TimeSpan sp = _dt.Subtract( _lastTriggerTime);
ReportMessage(sp.Seconds.ToString() );
log.Info("sp:" + sp.Seconds.ToString());
if(sp.Seconds>30)
{
_lastTriggerTime=DateTime.Now;
_ht=new Hashtable();
log.Info("SACHandlers.xml file update!!");
try
{
_ht=ReloadSacInfo();
}
catch(Exception ex)
{
msg="Reload Sac info from xml fail!!" + ex.Message;
// _reentryLock=false;
log.Error(msg);
ReportMessage(msg);
//_cnt=0;
}
//_cnt=0;
}
//_reentryLock=false;
Monitor.Exit(this);
No matter what way I use it will trigger twice even using
lock,Monitor,timespan check,lock variable .. The IDE will run the same
code twice(is it because they are triggered almost at the same time?so
monitor,lock is useless here?) when you step over in debug mode...
This drives me crazy.
So far, I think I need to use a flag and a timer to check, I cannot do
anything in OnChanged method, I think I only need to put a
isFileChanged flag there and use a timer to check that flag, if it
changes, I will do something....
Too bad solution, Could someone here have a better solution?
Thanks....