SequentialActionQueue in C#

By on 7/15/2011

A while ago, I created a clone on Google Code of the Stateless library because I wanted to use it in a .NET 4.0 project, and the current distribution was using VS 2008. After I did that, I started playing around with the library. Specifically, I wanted a way to have multiple state machines, and be able to process triggers and state changes in parallel. The problem of course is that although you can usually easily process state changes from different state machines in parallel, you can only process multiple triggers for a single state machine sequentially.

So I added a ParallelExample project to the solution and started experimenting. The end result is an easy to use class called SequentialActionQueue. Usually when you need to synchronize access to a resource, you end up putting a lock section around your code so that only one thread may access it at a time. However things get more complex if you need to synchronize multiple sections of the code (ex. multiple methods in a class where only one may run at a time). This is classic thread-safety issues, and the dragons that lie in those waters. However, With the SequentialActionQueue, you can simply instantiate the class and proxy all actions through it and be guaranteed that everything will run safely one after the other.
private SequentialActionQueue queue = new SequentialActionQueue();
private int counter =0;

public void Add(int i) { queue.Enqueue(() => counter += i); }

public void Subtract(int i) { queue.Enqueue(() => counter -= i); }
The above is a simplified example which emulates the ability to use Interlocked to safely increment/decrement a number. I'd love to get some thoughts on the class ... I wrote a few tests in the sample project, but that's not to say there won't be bugs in it, would love to hear your feedback :-)  

See more in the archives