C# – BackgroundWorker and Timer, handling one item at a time

backgroundworkercwinforms

My app monitors a directory where users can upload a file. When a new file is detected it is added to a queue. I have a timer that runs through the queue and determines if the file has finished uploading. If there are any files that are complete it will take the most recent and begin running a background task (using BackgroundWorker).

My problem is that I don't know how to handle the timer while the background task is running. For example, if the timer is set to 10 seconds and the background worker is still working I want the timer to skip execution of another background worker until its next iteration.

Also, the information for each task is stored in the Queue (a ListView control) and I pass the ListViewItem to the background worker. I'm curious if passing the ListViewItem has any side effects.

Thanks!

Best Answer

You could store ready-to-process files in another queue (like a Queue< string> ) and have the BgWorker continuously poll that Queue. You might get better performance too, less idle time. You will have to protect the Queue (with Monitor) and have the BgWorker use Monitor.Wait when the Queue is empty.

To get an idea, look for Marc Gravell's answer on this question.

Related Topic