Listener being called twice

조회 수: 2 (최근 30일)
Victor Lim
Victor Lim 2015년 2월 18일
편집: per isakson 2015년 2월 19일
I created a listener to monitor changes to a file. When I make a change to that file the function that is called from the listener runs twice when it should run once. Here is the code for the listener. The function eventhandlerChanged just displays the word 'changed'.
fileObj = System.IO.FileSystemWatcher('c:\Temp')
fileObj.Filter = 'test.txt'
fileObj.EnableRaisingEvents = true
lh=addlistener(fileObj,'Changed',@eventhandlerChanged)

답변 (2개)

per isakson
per isakson 2015년 2월 18일
The FileSystemWatcher documentation says that a simple file operation can
raise multiple events.
To turn off the event handler, type: fileObj.EnableRaisingEvents = false;
  댓글 수: 3
per isakson
per isakson 2015년 2월 18일
I don't know! However, these words in the documentation indicate that what you see is expected under some circumstances. Furthermore, the documentation refers to FileSystemWatcher Class or similar.
per isakson
per isakson 2015년 2월 19일
편집: per isakson 2015년 2월 19일
Did you read the documentation on
>> fileObj.NotifyFilter
ans =
FileName, DirectoryName, LastWrite

댓글을 달려면 로그인하십시오.


Guillaume
Guillaume 2015년 2월 19일
As per isakson says, this is a possible behaviour of the FileSystemWatcher. There's nothing you can do to stop the event being raised multiple time on a file modification.
Therefore, what you must do is make your event handler more resilient to this possibility. A fairly simple way would be to store the filename and timestamp of the call to your handler. If the filename is the same and the time elapsed between two calls is too short, simply not process again.
Another option is to implement some sort of queue of files to process, delayed by a few seconds. If in the queue the same file is present several times in a row, just collapse them all into one event.

카테고리

Help CenterFile Exchange에서 Scope Variables and Generate Names에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by