According to MSDN, Dispatcher
provides services for managing the queue of work items for a thread.
A simple question. I want to use Dispatcher
just for that: as a queue of work items (posted via Dispatcher.BeginInvoke
) which my background thread will serve in a serial manner.
I don't want to make this thread an STA thread and I don't need to pump Windows messages on it. There will be no UI on this thread.
Is it a legitimate way of using Dispatcher
?
Is it a legitimate way of using Dispatcher?
You could use a secondary thread with a Dispatcher
, but it's rather uncommon. This is usually done so that different parts of the UI run on different UI threads. A dispatcher thread will process Windows messages, and must be STA. Also, technically speaking the processing isn't strictly FIFO since dispatched items are queued with a priority.
That said, even though it wasn't designed to be used without a UI, you could use it that way.
Alternatives:
1) AsyncContextThread
is a simple thread with a work queue from my AsyncEx NuGet library:
private readonly AsyncContextThread _thread = new AsyncContextThread();
...
_thread.Factory.StartNew(() => { ... });
The AsyncContextThread
type provides a SynchronizationContext
for the code it runs, so async
continuations will resume on the same thread by default.
2) If it only matters that the requests are processed serially, and doesn't actually matter which thread they run on, then you can use a task scheduler to instruct the thread pool to run your requests one at a time, as such:
private readonly TaskFactory _factory = new TaskFactory(
new ConcurrentExclusiveSchedulerPair().ExclusiveScheduler);
_factory.StartNew(() => { ... });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With