I'm currently working on a a project and I have a need to queue some jobs for processing, here's the requirement:
- Jobs must be processed one at a time
- A queued item must be able to be waited on
So I want something akin to:
Task<result> QueueJob(params here)
{
/// Queue the job and somehow return a waitable task that will wait until the queued job has been executed and return the result.
}
I've tried having a background running task that just pulls items off a queue and processes the job, but the difficulty is getting from a background task to the method.
If need be I could go the route of just requesting a completion callback in the QueueJob method, but it'd be great if I could get a transparent Task back that allows you to wait on the job to be processed (even if there are jobs before it in the queue).
I would go for something like this:
Depending on the type of app that is using it, you could switch out the BlockingCollection/ConcurrentQueue for something simpler (eg just a plain queue). You can also adjust the signature of the "AddTask" method depending on what sort of methods/parameters you will be queueing up...
Func<T>
takes no parameters and returns a value of type T. The jobs are run one by one and you can wait on the returned task to get the result.You might find
TaskCompletionSource<T>
useful, it can be used to create aTask
that completes exactly when you want it to. If you combine it withBlockingCollection<T>
, you will get your queue: