SYSK 356: How To Execute A Workflow Synchronously Without waitHandle.WaitOne()

Consider the following code snippet frequently found in sample applications, code snippets and published articles:

 

using (WorkflowRuntime wr = new WorkflowRuntime("WorkflowRuntimeConfig"))

{

    wr.StartRuntime();

    using (System.Threading.AutoResetEvent waitHandle = new System.Threading.AutoResetEvent(false))

    {

        wr.WorkflowCompleted += delegate(object s, WorkflowCompletedEventArgs args) { waitHandle.Set(); };

        wr.WorkflowTerminated += delegate(object s, WorkflowTerminatedEventArgs args)

        {

            System.Diagnostics.Debug.WriteLine(args.Exception.ToString());

            waitHandle.Set();

        };

        wr.WorkflowAborted += delegate(object s, WorkflowEventArgs args) { waitHandle.Set(); };

        WorkflowInstance w = wr.CreateWorkflow(typeof(YourNamespace.YourWorkflow), parameters);

        w.Start();

        waitHandle.WaitOne();

    }

}

 

 

In essence, all that’s needed is to run a workflow synchronously…

 

Since you’re blocking the tread anyway, my recommendation is to simply run the workflow on the same thread. It could be easily done by using the ManualWorkflowSchedulerService, transforming the code above into this:

 

 

using (WorkflowRuntime wr = new WorkflowRuntime("WorkflowRuntimeConfig"))

{

    wr.StartRuntime();

    ManualWorkflowSchedulerService scheduler = wr.GetService<ManualWorkflowSchedulerService>();

    WorkflowInstance w = wr.CreateWorkflow(typeof(YourNamespace.YourWorkflow), parameters);

    w.Start();

   

    scheduler.RunWorkflow(w.InstanceId);

}

 

And that’s all…