Tuesday, December 17, 2013

Run Workflow Application Synchronously to Check the Completion State

If you come across this article, you are probably writing a Unit Test for your workflow, in which you need to know when workflow processing is completed. You also may want to examine the CompletionState value from the Complete event, otherwise you would use WorkflowInvoker instead of WorkflowApplication...

The solution turns out to be fairly simple: use ManualResetEvent. Okay, let's get to the code and that will be it:

using System.Activities;
using System.Threading;

[TestMethod]
public void TestExternalCancellationSimple() {
    var wf = new SomeActivity {
        ...
    };

    ActivityInstanceState state = ActivityInstanceState.Executing;
    var mre = new ManualResetEvent(false);

    var app = new WorkflowApplication(wf) {
        Completed = (e) => {
            state = e.CompletionState;
            mre.Set();
        }
    };
    app.Run();
    Thread.Sleep(500);  // wait a bit and then cancel the workflow
    app.Cancel();

    mre.WaitOne();

    Assert.AreEqual(ActivityInstanceState.Canceled, state);
}

UPDATE: Everything had been invented known even before we came in this world... Very similar code to the snippet above can be found in WF's Getting Started How to: Run a Workflow, with the only difference is that in MSDN they use AutoResetEvent, which is, technically speaking more correct, though doesn't make any difference if you call WaitOne only once.

No comments:

Post a Comment