I have the following code which lets me execute a workflow. This could be called repeatedly. And often is. It’s also living in a webservice, so there could be multiple calls to it at the same time. This currently works. But it’s slow, since instantiating a WorkflowRuntime each time is very slow.
How can I improve this?
public class ApprovalWorkflowRunner : IApprovalWorkflowRunner
{
private static ILogger Logger { get; set; }
private static IRepository Repository { get; set; }
public ApprovalWorkflowRunner(ILogger logger, IRepository repository)
{
Logger = logger;
Repository = repository;
}
public Request Execute(Action action)
{
var request = new Request();
using (var workflowRuntime = new WorkflowRuntime())
{
workflowRuntime.StartRuntime();
var waitHandle = new AutoResetEvent(false);
workflowRuntime.WorkflowCompleted += ((sender, e) =>
{
waitHandle.Set();
request = e.OutputParameters["gRequest"] as Request;
});
workflowRuntime.WorkflowTerminated += ((sender, e) =>
{
waitHandle.Set();
Logger.LogError(e.Exception, true, action.Serialize());
});
var parameters = new Dictionary<string, object>
{
{"RepositoryInstance", Repository},
{"RequestID", action.RequestID.ToString()},
{"ActionCode", action.ToString()}
};
var instance = workflowRuntime.CreateWorkflow(typeof (ApprovalFlow), parameters);
instance.Start();
waitHandle.WaitOne();
}
return request;
}
}
Ideally, I’d like to keep one copy of the WorkflowRuntime around. But since I’m passing other objects around in the CreateWorkflow function and WorkflowCompleted event, I don’t see how it would work.
…am I missing something simple here, there’s a good chance my brain didn’t tell my body it wasn’t showing up to work today.
One runtime can run many workflows at the same time. As per the answer here:
That page shows some code for a WorkflowRuntime factory that I will include below, that I believe was originally taken from the Windows Workflow Foundation Step by Step Book
You would simply call
EDIT:
OK sorry. You can try checking the instance is the one you expect, and returning if it’s not. Please note this code is untested, just trying to get the idea across.