Monday, February 7, 2011

Thread Dispatcher

WPF has the concept of a DispatcherObject underpinning every UI object. The Dispatcher's task is to marshall operations from all threads onto the DispatcherObject's owner thread. This is needed because Windows UI programming is not thread safe.


I have run into multi-threading problems with certain libraries which had thread affinity requirements. WPF's Dispatcher pattern appealed to me and I wanted to have an attempt at writing my own simple implementation. Sample usage:



var td = new ThreadDispatcher();
td.Invoke(() => someObject.Action());
var result = td.Invoke(() => someObject.ShouldQuit());
if(result == true)
td.Stop();

The code for the ThreadDispatcher is here: ThreadDispatcher.cs


The next step was to cater for (hypothetical) situations where I had lots of non-thread-safe objects. These objects would need to be always accessed on the same thread, but there was no requirement for each object to have a unique thread. I created a ThreadDispatcherPool implementation based on .net's ThreadPool. The use it, you just request a ThreadDispatcher from the ThreadPool when you create a new Non-thread-safe object:



ThreadDispatcherPool.GetThreadDispatcher();

The code for ThreadDispatcherPool is here: ThreadDispatcherPool.cs


(A potential problem with the ThreadDispatcherPool is that a client could call Stop() on a shared ThreadDispatcher...)