I have a windows service which executes a job asynchronously every few minutes, sometimes the windows service executes and the previous job has not finished, using threading is there a way to queue the new job if the previous one hasnt finished so that it starts running when the first job finishes?
Asked
Active
Viewed 683 times
2
-
1Sounds like you would have to be careful not to get an infinitely growing backlog of tasks if they are being queued faster than they can complete. Make sure a max number to queue is present somewhere (for example just one!) or just take the easy way out and prevent a new job starting if an old one is present. – Matt Jan 14 '11 at 16:06
2 Answers
5
You could create your own producer/consumer queue of jobs - effectively a single-thread threadpool.
This is easy to do in .NET 4 using BlockingCollection<T>
; before then it's a little trickier, but not too bad.

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
-
Unfortunately I'm using 3.5 do you have a link to an example in 3.5? thanks – ryudice Jan 14 '11 at 15:56
-
@ryudice: There's some sample code here: http://stackoverflow.com/questions/530211/creating-a-blocking-queuet-in-net/530228#530228 – Jon Skeet Jan 14 '11 at 15:58
-
@Jon: With 3.5, should the OP use Task Parallel Lib, check `cancelToken.IsCancellationRequested` and store task in Queue
or List – IAbstract Jan 14 '11 at 16:00is the task is currently busy? -
@IAbstract: How would the OP use the Task Parallel Library from 3.5? I know that Reactive Extensions comes with *some* of the TPL, but not all of it as far as I'm aware. – Jon Skeet Jan 14 '11 at 16:02
-
@Jon: I was under the impression that TPL was available for 3.5 - http://blogs.msdn.com/b/pfxteam/archive/2008/06/02/8567802.aspx – IAbstract Jan 14 '11 at 16:04
-
@IAbstract: That's a CTP. Not a full release you should rely on in production. Note the bit in blue on that page - the CTP is no longer available, and the subset which is part of Parallel Extensions is unsupported. – Jon Skeet Jan 14 '11 at 16:05
-
@Jon: ah...I'm glad I didn't try to take someone's advice about trying to use it: http://stackoverflow.com/questions/4555307/enabling-queuet-with-concurrency/4555395#4555395 – IAbstract Jan 14 '11 at 16:10
0
you have to implement the queue in main controlling service. on the completion of thread and/or periodicaly you can check queue and start next task.

Artemiy
- 1,969
- 14
- 19