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


    protected override void Execute(CodeActivityContext context)


        var asyncContext = context.SetupAsyncOperationBlock();

        var task = new Task(DoAsyncWork, asyncContext);




    private static void DoAsyncWork(object state)


        var asyncContext = (AsyncOperationContext)state;


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



        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.





2 thoughts on “Basic asynchronous work in Windows Workflow Foundation 4

  1. I’ve just print-previewed this page and the code doesn’t appear. All of the code blocks on the other pages appeared in Print Preview. Is there something different about it?

Leave a Reply

Your email address will not be published. Required fields are marked *