Share via


ASP.Net: How to Use SynchronizationContext to Host Workflows

Applications running in ASP.Net won't work properly if they spawn new threads, but to get the most functionality from [[Windows Workflow Foundation]], WorkflowApplication starts workflows on new threads by default. The WorkflowApplication object has a member called SynchronizationContext that can be used to override this default functionality.

The following code snippet demonstrates how to implement SynchronizationContext to keep the workflow 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();
}

 

References

 The following thread discusses this issue further: http://social.msdn.microsoft.com/Forums/en-US/wfprerelease/thread/dca30678-9b26-4fe0-b347-f12a702c8e62