Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Dispatcher on non-UI thread

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?

like image 834
avo Avatar asked Sep 19 '25 15:09

avo


1 Answers

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(() => { ... });
like image 181
Stephen Cleary Avatar answered Sep 22 '25 07:09

Stephen Cleary