Is there something in the framework that would allow me to asynchronously execute a queue of delegates?
What I mean by that is I want the delegates to execute one at a time in the order they are queued but I want this whole process to run asynchronously. The queue is not fixed either, additional delegates would be added periodically and should be processed as soon as it reaches the top of the queue.
I don't need to use a Queue
in particular, it's just how I would describe the desired behavior.
I could write something myself to do it but if there is something built in I could use instead that would be better.
I briefly looked at ThreadPool.QueueUserWorkItem
as it allows executing in order but could find a satisfactory way to prevent more than one execution at a time.
I'd implement this as a custom task scheduler. You could then queue and run your delegates as tasks, which would give you all benefits of exception handling, cancellation, and
async/await
.Implementing a task scheduler which would execute your delegates in the serial order is quite simple, using
BlockingCollection
. TheSerialTaskScheduler
below is a simplified version of Stephen Toub'sStaTaskScheduler
:Output:
You can use
TPL dataflow
'sActionBlock
and simply queue up a class that holds aDelegate
and a lists of parameters. TheActionBlock
will simply executes those delegates one at a time.An even easier option would be to use an
ActionBlock
ofAction
, but that forces you to capture the parameters: