Search code examples
c#queuefilesystemwatchersequential

How can I sequentially process elements from a queue in C# .NET


I am writing software for Windows in Visual Studio 2012, coded in C#.

By using the FileSystemWatcher class, I am monitoring a directory for changes: if one or more new files are added to the directory, an event gets fired by FileSystemEventHandler class.

This event adds the file name(s) to an array.

I then want to process the array, that is: process every file (access via the file name) in the array and do something with the file.

Now: I need to make sure the file processing happens sequentially. Look at file 1, process it, and only when this is finished, look at file 2, process it, and so on.

The file processing takes about 5 seconds per file. Meanwhile, new files can be added to the directory and thus the FileSystemEventHandler class will fire because of these changes. But I do not want this to happen - there should always only be one file at a time that gets processed - regardless of how many times the event for changes gets fired!

Can anyone provide me with a pattern (or code snippet) for this, please?!


Solution

  • I think following class would be optimal,

    BlockingCollection<T> Class

    Provides blocking and bounding capabilities for thread-safe collections that implement IProducerConsumerCollection.

    It acts as concurrent queue and you can process items async using Tasks.

    Alternative would be ConcurrentQueue<T>, But The BlockingCollection gives you two important features

    It's thread-safe

    When you call Take(), it will block(i.e. wait until something is in the queue) for you, so you don't have to write any code with ManualResetEvents and the like, which is a nice simplification.