Can I run a FileSystemWatcher on another thread

davearia

Centurion
Joined
Jan 4, 2005
Messages
184
Hi All,

I have been writing a little application that watches my documents and nay files/folders that are changed/created/deleted/renamed are copied to the main server. As a back up process it seems to work great. I have subclassed the FileSystemWatcher and put all of the logic in there and in my form all I need is:
Visual Basic:
 fileSystemWatcher fsw = new fileSystemWatcher(true, true, true, true, @"\\source\", @"\\destination", true);
 fsw.ShowProcess += new fileSystemWatcher.ShowProcessEventHandler(ShowProcess);
 fsw.SynchronizingObject = this;

The code is working great with one exception. If I am doing a big process, let's say copying 1GB of music the UI is frozen as the UI thread is busy.

Is it possible to put this process to a separate thread possibly using a background worker? If so can anyone give a brief example of how to do this?

Thanks, Dave.
 
If you need to work in a different thread, something like should work.

You may need to use a delagate to get the updateUI event to work correctly.

C#:
System.Threading.Thread t;

protected void button_click(...)
{
    t = new System.Threading.Thread(runSync);
    t.Start();
}

void runSync()
{
    fileSystemWatcher fsw = new fileSystemWatcher(true, true, true, true, @"\\source\", @"\\destination", true);
    fsw.ShowProcess += new fileSystemWatcher.ShowProcessEventHandler(ShowProcess);
    fsw.SynchronizingObject = this;
}
 
Hi Nate,

Thanks for your reply. I have not been working on this code for a while. I got a bit stuck with to be honest.

Apart from the issue you have posted for the app was working well enough. Until I decided to create 2 instances of the file system watch class I have written. The first watches a folder on my local machines and copies/changes/deletes/updates all files in the directory to a directory on the server. The 2nd instance watches the directory on the server and performs the same operations as the first but this time to a networked hard drive.

The events went nuts and the app just locked. Would people say that using the FileSystemWatcher class as I have here is abusing this class or am I trying to do something that is within its capabilities?
 
I don't know, but my guess is that you created a "race" condition, update made to client was replicated to server, and the server was replicated to the network drive. I think that the issue may have been doing both at once.

What size file did you test with? I'd try a 1kb text file since even a race condition there would only last a few seconds.

You may want to schedule events to do these file transfers.
 
Back
Top