Reputation: 75
I need an advice on how to write a windows service application that would monitor changes to a certain folder on a drive and copy changed and newly created files to a certain location. Now, I am going to use FileSystemWatcher for this purpose, but I wonder what would be the best way to deal with the situation when multiple files need to be copied simultaneously? For example, one huge file is still being copied and the event is fired again? Do I need to form some sort of a queue and whenever one file is finished being copied, start the next one? Or maybe create a new thread for each file and take care of the copying in that thread? Also, should I use the File.Copy method, or is there a better/faster way?
Upvotes: 3
Views: 489
Reputation: 26
Instead of managing a queue and workers yourself, why not just dispatch to the Thread Pool?
// event handler of FS Watcher
await Task.Run(() => File.Copy(...));
Upvotes: 0
Reputation: 174457
I would go with the queue. The queue is filled with the file name by the event handler and a background thread processes the queue.
If you are using .NET 4, you can use the ConcurrentQueue<T>
and be thread safe.
Non-compiling sample code:
class AsyncFileCopier
{
BackgroundWorker _worker;
void OnNewFile(string fileName)
{
_queue.Enqueue(fileName);
EnsureWorkerIsRunning();
}
void EnsureWorkerIsRunning()
{
if(!_worker.IsBusy)
_worker.RunWorkerAsync();
}
void OnWorkerDoWork(...)
{
string fileName;
while(_queue.TryDequeue(out fileName)
{
CopyFile(fileName);
}
}
}
Upvotes: 1