Multiple occurences of same code

  • Thread starter Thread starter Rob Oldfield
  • Start date Start date
R

Rob Oldfield

I have an app that seems to be fine at the moment, but I'm a little worried
that I'm setting myself up to run into a brick wall. The basic outline of
the code is that a FileSystemWatcher keeps an eye on a folder, when a file
appears, it gets processed. Processing takes around 5 seconds.

My potential problem is that files can get created in the folder every two
seconds.... so while the code is processing the first file then the second
turns up. In testing, I haven't managed to break it yet by dumping lots of
files into the folder at the same time.... but should I be doing something
like using threading to handle each occurence of the code? In practical
terms... this is an app that is used internally by my firm and I would doubt
if there would ever be more than 5 files created at one time (i.e. over 10
seconds).

Any thoughts?
 
You can make two threads: one, called by FileSystemWatcher, adds new files
to a queue, and the other thread takes files from the queue and processes
them, one by one. Alternatively you can process each file in a separate
thread started directly by FSW.
 
Hey Rob,

The FileSystemWatcher raises all events on threads obtained from the
ThreadPool (through the use of ThreadPool.BindHandle). This means that none
of the callbacks from FileSystemWatcher run on your applications main thread
(it does seem that most of the time the events are raised on the same thread
from the ThreadPool though). The threadpool queues the callbacks
automatically and you only have to worry if the processing of each file
manipulates some data that must be synchronized between threads.

If you want the callbacks to be handled by a e.g. a WinForm, you can set the
SynchronizingObject property of the FileSystemWatcher to a Form instance
(which implements ISynchronizeInvoke). Then all callbacks will be
synchronized and executed on the thread on which the form was created.

Regards, Jakob.
 
Back
Top