This post originated from an RSS feed registered with .NET Buzz
by Udi Dahan.
Original Post: On application responsiveness
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.
Dr. Dobb's recently published an article on "Application Responsiveness" by Joe Duffy where he gives a very thorough treatment of threading issues in UIs. I felt that the discussion of the solutions was a bit light, but there was one solution missing that, in my opinion, is more important than all the rest.
The kinds of systems that I work on almost always have the client side being asynchronously updated by events published by a server. If there's one thing I've learned, its that threading is a HARD problem. What makes it hard is that it adds another dimension to the complexity of the system. Which is why I'll do almost anything to have the code that I'm looking at behave single-threaded.
The solution involved first separating out classes that will be touched by only one thread. This means that all view classes (in MVC terms) will be accessed only on the control thread. Secondly, classes that receive information asynchronously from the server will only run on the background thread. Classes in the model (in MVC terms) will not be thread-aware, therefore it is the responsibility of other classes to interact with the model in a thread-safe manner. All other classes, like the controllers (in MVC terms) will be run on both/multiple threads. Despite the need to marshal a call from the background thread to the foreground one (which has been done to death), these controllers have state that needs to be protected.
Enter the ContextBoundObject. This framework class enables you to quite simply put a [Synchronization] attribute on a class that inherits from it, and voila, its thread safe. Not only that, but it will share a single lock with all the other objects that inherit from ContextBoundObject, as long as they're in the same Synchronization Domain. Don't worry, it's easy. Just have a single object that is also a ContextBoundObject be the one that causes all others to be created. If you're using a container like spring, then the first object would be that which asks spring to initialize.
OK, so technologically - you're all set. But doing the design according to the constraints mentioned above isn't trivial. Especially when it comes to the Model objects. But believe me, it's much easier than an endless hunt after deadlocks and race conditions.