Sunday, October 26, 2008

Synchronizing Workflow Instances

In a multi threaded program, where different threads use a shared resource, the access to this shared resource needs to be synchronized. Most if not all programming languages or parallel programming systems provide some kind of synchronization mechanisms which help the programmer to protect shared resources and avoid race conditions. Unfortunately the Workflow Foundation (a system that is inherently multi threaded) does not provide a way to synchronize activities across workflow instances out of the box. Of course there is the SynchronizationScopeActivity, but it's only usefull when you need to synchronize parallel activities running in the same workflow instance.
One good reason for the absence of this kind of feature is the fact that if you have a shared resource then you usually access it through a runtime service. Synchronizing the access to the resource is the responsibility of the runtime service and not the responsibility of the workflow.
But nevertheless if you need to synchronize workflow activities across multiple instances or even different workflows you may find this usefull. It's an activity similar to the SynchronizationScopeActivity provided by WF except it synchronizes its child activities between different instances of a workflow.
To use this activity in you workflows you need to add an instance of a runtime service (CustomWorkflowActivities.SynchronizationService) provided with the activity to the workflow runtime first:
WorkflowRuntime workflowRuntime = new WorkflowRuntime();
workflowRuntime.AddService(
  new CustomWorkflowActivities.SynchronizationService(
    workflowRuntime));
Then just insert a RealSynchronizationScope activity into your workflow, set its SharingName property to some unique-within-the-workflow-engine string, and drag activities you wish to synchronize onto the RealSynchronizationScope activity. That's it! The workflow runtime will now serialize the execution of any activities inside your RealSynchronizationScope activity across workflow instances.