how to synchronously execute workflow using Elsa workflow engine

1k views Asked by At

Elsa workflow supports asynchronously execution of workflow, so we can't get the result on spot, workflow execution performed by a thread, and response back instantly. So after completing workflow execution i'm unable to get actual output of workflow. So is there any way to perform workflow execution synchronously so that I can get the final output.

1

There are 1 answers

0
Sipke Schoorstra On

You can run your workflow synchronously using IWorkflowRunner.RunWorkflowAsync, which returns a RunWorkflowResult that contains the executed WorkflowInstance, which contains output that was set by the workflow, if any.

The RunWorkflowAsync takes the following parameters:

  • IWorkflowBlueprint - the workflow blueprint to run.
  • WorkflowInstance - a workflow instance of the workflow blueprint.
  • ActivityId - Optional. If your workflow has more than one starting activity, you need to specify which one to use.
  • WorkflowInput - Optional. If your workflow expects input, this is where you provide it.

To get a workflow blueprint, use IWorkflowRegistry to find a workflow by name or by type (which is more convenient in case you have your workflow built using the fluent API).

For example, if you have a workflow named "HelloWorld", this is how you get the workflow blueprint:

var workflowBlueprint = await _workflowRegistry.FindByNameAsync("HelloWorld", VersionOptions.Published);

To create a workflow instance, although you could simply instantiate a new WorkflowInstance using its constructor, the simplest way is to use IWorkflowFactory like this:

var workflowInstance = await _workflowFactory.InstantiateAsync(workflowBlueprint);

With both the workflow blueprint and workflow instance at the ready, you can now run the workflow:

var result = await _workflowRunner.RunWorkflowAsync(workflowBlueprint, workflowInstance);

As an alternative to this low-level prepping of workflow execution, you can also use a higher-level service that does all this on one go.

For example, if you have a workflow created using the fluent API (i.e. some IWorkflow implementation) called HelloWorldWorkflow, then you can run the workflow using IBuildsAndStartsWorkflow, like this:

var result = await _buildsAndStartsWorkflow.BuildAndStartWorkflowAsync<HelloWorldWorkflow>();

That will do the steps I explained earlier for you (and run the workflow synchronously).

Yet another way is to use the higher-level service called IWorkflowLaunchpad, which has various methods to locate the workflow (or workflows) you want to execute.

For example, if you know the workflow definition ID you want to execute synchronously, here's how you would do it:

var myWorkflowDefinitionId = "...";
var result = await _workflowLaunchpad.FindAndExecuteStartableWorkflowAsync(myWorkflowDefinitionId);