I have a PollingService that starts a Task
every minute. This Task
will get all the mails in my Folder and then loop through each processing them. There is a possibility that a Task
will be kicked off while the last Task
is still running. This will result in the mails being processed twice and create duplicate data. How to prevent this?
Asked
Active
Viewed 207 times
1

user3261212
- 391
- 2
- 15
-
1Can you post your code? – Johnathan Barclay Jun 15 '20 at 14:58
-
Use `Quartz` or `Hangfire` for task scheduling. – Guru Stron Jun 15 '20 at 14:58
-
1Read this post: https://stackoverflow.com/questions/34519/what-is-a-semaphore – Dani Jun 15 '20 at 15:11
-
You could consider replacing the timer with an infinite loop, containing a `Task.Delay`. This would eliminate the possibility of overlapping executions. You can find examples [here](https://stackoverflow.com/questions/61192103/async-system-threading-timer-sometimes-throwing-null-exception/61193299#61193299) and [here](https://stackoverflow.com/questions/61831541/c-sharp-wpf-program-button-click-run-a-task-until-another-button-click-stop/61842206#61842206). – Theodor Zoulias Jun 15 '20 at 18:31
1 Answers
1
One option would be to use a limited concurrency task scheduler (see example). This can ensure that each task is run sequentially.
Another option is to start a thread that waits on a autoResetEvent in a loop. The timer would simply trigger the autoResetEvent, releasing the thread to do its job. The downside is that this would consume a whole thread.
A third option would be to set a flag when starting the work, and reset it when it is complete. The timer could then skip starting the task if the flag is set. You might want to use lock or interlocked to avoid thread safety issues.
There might be some issues when adding items just before the task completes, but if it is run on a timer I would assume all items would be processed eventually.

JonasH
- 28,608
- 2
- 10
- 23