This post originated from an RSS feed registered with .NET Buzz
by Udi Dahan.
Original Post: Multithreaded evolution
Feed Title: Udi Dahan - The Software Simplist
Feed URL: http://feeds.feedburner.com/UdiDahan-TheSoftwareSimplist
Feed Description: I am a software simplist. I make this beast of architecting, analysing, designing, developing, testing, managing, deploying software systems simple.
This blog is about how I do it.
Ayende's taking my ThreadSafeQueue for a drive and seems to like the journey so far.
I'd like to push the envelope a little bit further. Once realizing that the thread is just receiving messages and acting on them, we can raise the level of abstraction a bit higher. Let's create an interface called IMessageSource to represent this abstraction. This interface would expose an event, MessageReceived which would return the message received. Code that would handle messages would just be bound to an IMessageSource without any knowledge that the messages came from a queue, or are being executed on a different thread - all that would be wrapped up in the implementation.
The implementation could be done by a QueueListener which would implement IMessageSource on top of the ThreadSafeQueue. QueueListener should also encapsulate the entire issue of creating a new thread.
A better separation of concerns would have a WorkerThread class which would encapsulate the basic System.Threading.Thread, and add the ability to stop the thread in a controlled manner. QueueListener would inherit from WorkerThread. The code would look something like this:
MessageHandler mh = new MessageHandler();
IMessageSource ms = GetMessageSource();
ms.MessageReceived += new MessageReceivedDelegate(mh.HandleMessage);
ms.Start();
and the method HandleMessage would look something like this:
public void HandleMessage(object message)
{
// write single-threaded code for handling the message here.
}
I'll try to put up the code for WorkerThread and QueueListener soon.