Monday, June 16, 2008

The Listen Activity Issue – State Machines

In the past couple of months, I’ve dedicated an amount of my free time to learn Windows Workflow Foundation. The Workflow concept was familiar to me and I was curious about this technology. So far, and there’s only been 6 months since I started this learning, I got to apply this technology a couple of times.

Why am I writing this post? Well, from all of the scenarios I came across until now, one of the most “tricky” ones is when there’s a timeout situation. Let me explain:

One of the most common issues every programmer has to deal with is the timeout situation. This situation happens all the time, whether it’s on a synchronous/asynchronous request, a lack of user intervention or even a hardware failure. What to do when there’s no response from a server? Should we wait for ever? Of course not: it’s a timeout!

Up until now, to deal with this, we’d probably implement a timer and when the time to wait for a response has ended, we should perform a set of actions to compensate this event (e.g.: Cancel the asynchronous request – most common). With Workflow Foundation, a good part of all the work needed to do this is already done! The Listen Activity:



The above picture shows the Listen Activity. What is it? Well, it’s a “block” that waits for “n” events and when one of them fires it resumes execution, going down the trail of the event that fired. The other ones are no longer to be “listen”. One of the events can be a delay (a.k.a. timer). Are you already picturing the “timeout situation”? It’s perfect! One event (or more) is what our application wants (e.g.: A document approval from a user) and the other event is the timeout!

So, why am I complaining? Well, the listen activity is available only for Sequential Workflows. That is, workflows that execute the activities sequentially and the execution of them can’t go back. My loved listen activity can’t be used on State Machine Workflows. According to Kenn Scribner, a software architect and instructor at Wintellect, who wrote Windows Workflow Fountation Step by Step, WF team decided to keep the listen activity out from state machine workflows because it could be a potential cause of deadlocks (witch are not easy to find). I can agree that it could lead to these “tricky” deadlocks, I can even imagine a few ones and tell you how to solve them (don’t ask), but one thing that I can’t understand is why aren’t we able to decide if we want the risk. I mean, we become software engineers for a reason! Solve complicated problems! To come up with solutions for the “hard stuff”!

Well, of course Microsoft doesn’t do things for no reason, and you can “go around” and implement the listen activity yourself (composite activity) or even use Parallel activity. But this is unnecessary work if we had the listen activity. I sure hope they’ll let us use the listen activity with state machine workflows in the next WF release.