Thursday, October 19, 2006 2:09 AM bart

WF - Working with events and the ListenActivity


This post builds upon the foundation created in yesterday's post about the HandleExternalEventActivity. Please follow the instructions in that post before continuing with this one. As you've learned from this previous post, waiting for an external event to occur is a very powerful mechanism to drive execution of a workflow. There are a lot of scenarios however where you'll want to wait for more than one event at the same time, or you want to timeout such a wait for an event to get raised. To make this kind of dreams reality, WF has the ListenActivity in its magic toolbox.

The demo

Take the solution you built in the previous post on working with events and go to Workflow1.cs's designer view. It should look like this:

Your next job is to transform this into the following:

An easy way to accomplish this is outlined below:

  • Add a ListenActivity below the WhileActivity.
  • Rename the left branch of the ListenActivity to clientArrived and the right branch to timeoutOccurred.
  • Drag and drop the clientArrival and doWork activities from the while loop to the left branch.
  • Delete the SequenceActivity from the WhileActivity's body.
  • Drag and drop the ListenActivity to the body of our WhileActivity.
  • Add a DelayActivity (set to 10 seconds) called timeout to the right branch, as well as a CodeActivity called oops with the following ExecuteCode handler code:

    Console.ForegroundColor = ConsoleColor.Cyan;
    Console.WriteLine("Oops! Timeout occurred"

Basically, the ListenActivity blocks till one branch completes. Notice you can add additional branches, e.g. to listen to three, four, ... events at the same time:

When you try to execute this workflow, you'll see timeouts occurring when the client waits to long to enter her name:

I'm sorry for the defaced console output, but hey that's not the goal of the demo is it?


Waiting for one event to occur is a common requirement; waiting for multiple events can be even a more common requirement. WF makes it really easy to do this, without having to mess around with threading and waithandles (even more: in a stateful long-running world relying on additional runtime services like persistence) using the ListenActivity. I bet you'll find yourself leveraging the power of this activity on a regular basis, especially in combination with a DelayActivity to model timeouts. Now you know everything about waiting for events in WF, it's time to wake up yourself and don't wait any longer to explore WF! Cheers! | Digg It | Technorati | Blinklist | Furl | reddit | DotNetKicks

Filed under: ,


No Comments