Basic asynchronous work in Windows Workflow Foundation 4

The whole asynchronous execution model in WF 4 has changed quite a bit from WF 3. Not really a surprise as this one of the areas where WF 3 was really hard to work with.

Below is a very simple example. It does nothing useful, it’s only task is to show how to get started with asynchronous work in WF 4.

class AsyncWorker : CodeActivity

{

protectedoverridevoid Execute(CodeActivityContext context)

{

var asyncContext = context.SetupAsyncOperationBlock();

var task = new Task(DoAsyncWork, asyncContext);

task.Start();

}

privatestaticvoid DoAsyncWork(object state)

{

var asyncContext = (AsyncOperationContext)state;

Console.WriteLine("Doing some work.");

Thread.Sleep(5000);

asyncContext.CompleteOperation((ctx, bm, s) => { }, null);

}

}

The important parts here are:

CodeActivityContext.SetupAsyncOperationBlock()

This basically tells the runtime that the activity is going to do something asynchronously and that the runtime should not continue with the next activity when the Execute() is finished. It also means that the workflow cannot be persisted until this operation is complete.

AsyncOperationContext.CompleteOperation()

This tells the workflow runtime that the operation is complete and that the next activity can be scheduled or the workflow may be persisted.

Because the workflow can’t be persisted this is designed for relatively short running operations. So something like saving some data via a WCF service. If you need the sort of asynchronous work where you might be waiting for day’s on an end user this is not the way to go. In that case you should be looking at bookmarks instead.