Short answer:
If you need to actually do work with Dispatcher
runtime components, such as System.Windows.Media.Imaging, then I have an answer for you. If you're not using Dispatcher
runtime components then don't even consider using the Dispatcher
runtime. Use the Task Parallel Library (TPL) instead.
Long answer:
I've built and use this DispatcherTaskScheduler
implementation in high volume production services. You can configure it with as many threads as you'd like it to have a pool of (default is number of cores) and it will take care of spinning up those threads, initializing them with the Dispatcher
runtime and then queuing and dispatching work to them. Works with great with TPL, TPL DataFlow, SynchronizationContext
style programming (e.g. async/await), etc.
Basic usage looks something like this:
Task.Factory.StartNew(() =>
{
// Do anything you want with Dispatcher components here
},
CancellationToken.None,
TaskCreationOptions.None,
DispatcherTaskFactory.Default);
If you configure your own instance (e.g. you want more threads) then just replace DispatcherTaskFactory.Default
with your instance instead. My advice is to not configure more threads than cores (just use the Default
instance) and make sure you try to only do Dispatcher
runtime work on these threads.
As I mentioned, I use this implementation in several parts of our software system related to image processing that are core to our business and endure high volume loads and it's proven absolutely bullet proof for us.
Finally, the disclaimer: Microsoft doesn't really support the Dispatcher
runtime being used like this.