FileSystemWatcher Locking Files

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

I have a FileSystemWatcher that fires an OnCreated event, during this event
I want to more the file that was created but it is always locked when I run
this as a windows service, if I run the same code as a Windows App then it
runs fine... Any ideas?

It seems to be the event that is causing the problem since even under the
Windows Service I can copy and move files outside of the event.
 
Neil said:
Hi,

I have a FileSystemWatcher that fires an OnCreated event, during this
event I want to more the file that was created but it is always
locked when I run this as a windows service, if I run the same code
as a Windows App then it runs fine... Any ideas?

It seems to be the event that is causing the problem since even under
the Windows Service I can copy and move files outside of the event.

The best action is not to access the file in the event handler ;-)

Seriously, put the code to move the file in another method, create a
delegate and call this delegate on a thread pool thread and then
immediately return from the handler. Unless you have a multi processor
machine, returning from the event handler should allow Windows to
release the lock before the thread pool thread gets called. To mitigate
against multiprocessor machines the method that moves the file could
handle the access issue by waiting for a bit (use Thread.Sleep) before
repeating the action. Thread.Sleep is important because it will wait the
specified time *and* the thread will relenquish its time slice to allow
another thread to run (hopefully the thread that has locked the file).

Richard
 
That worked a treat, thanks.

Kinda weird that it locks as a service but not as a windows app... oh well
 
Neil said:
That worked a treat, thanks.

I'm glad it did :-)
Kinda weird that it locks as a service but not as a windows app... oh
well

It is. I don't know why, and I don't really have the time to investigate
why (.NET is no longer my 'day job').

Richard
 
Back
Top