I have a C# 4 application that is subscribing for an event which I expect to be raised a very large number of times in quick succession. Each time it is raised a bit of work is required to be done that I don’t really want to block the event thread with.
It feels like I should pass off this “chunk” of work to a background thread / task and allow the event thread to continue, however I also need to make sure that too many threads aren’t created as, as I say, I expect this event to be raised a lot of times quickly.
Is there a recognized pattern or recommended approach for passing off event handler workload to background threads but limiting the amount of threads created?
It feels like there should be some way of using the Task Parallel Library for this, but can’t find anything that does exactly what I need at the moment.
Let me know if anyone needs any more information, as I appreciate I’ve been quite general with what I’ve said.
Thanks.
If the “bit of work” that you want to perform each time the event is raised is small and mostly CPU-bound, then just start a
Taskeach time. TheThreadPoolwill determine the optimal number of threads to use, which will most likely be close to the number of CPU cores you have. You don’t have to worry about limiting the degree of parallelism in this case.If the work for each raise can take a long time or if it’s mostly IO-bound, then you should manually limit the degree of parallelism. One way to do that would be to have a small number of threads that block if there’s no work, and otherwise process the events from a queue. You could achieve this by using
BlockingCollection.Possibly the best option, if you can use .Net 4.5, is to use
ActionBlockfrom TPL Dataflow withMaximumDegreeOfParallelismset. With it, you won’t waste any threads when there is no work and you can set the maximum number of threads to be used (or not).