Share via


How to Use SynchronizationContext for Hosting Workflows in ASP.Net

Overview

Applications hosted in ASP.Net should not run processes which spawn new threads.  In order to gain the most functionality out of [[Windows Workflow Foundation]], workflows they need to be hosted using WorkflowApplication, which spawns new threads by default. WorkflowApplication has a member called SynchronizationContext that can be used to override this default behavior.

The following code snippet demonstrates how to add a synchronization context to a WorkflowApplication object in order to keep the workflow process on the calling thread.

protected void Page_Load(object sender, EventArgs e){    Activity workflow = new Sequence    {        Activities =        {            new Assign<string>            {                To = new OutArgument<string>(context => this.TextBox1.Text),                Value = "Default"            },            new Delay { Duration = TimeSpan.FromSeconds(10) },            new Assign<string>            {                To = new OutArgument<string>(context => this.TextBox1.Text),                Value = "Hello"            }        }    };     WorkflowApplication application = new WorkflowApplication(workflow);    SynchronizationContext syncContext = SynchronizationContext.Current;    application.Completed = delegate { syncContext.OperationCompleted(); };    application.SynchronizationContext = syncContext;     syncContext.OperationStarted();    application.Run();}

This issue is further discussed in the following forum thread:

http://social.msdn.microsoft.com/Forums/en-US/wfprerelease/thread/dca30678-9b26-4fe0-b347-f12a702c8e62

See Also