Search code examples
c#asynchronousdynamics-crmworkflow

How to Execute MSCRM Workflow Asynchronously in C#


Below is my C# snippet that triggers a mscrm workflow.

public void GenerateWorkflow(string selectedIDs, IOrganizationService service)
{
    var request = new OrganizationRequest()
    {
        RequestName = "GenerateWorkflow",
    };
    request.Parameters.Add("SelectedIDs", selectedIDs);

    var response = service.Execute(request);
    if (response.Results != null && response.Results.Count > 0)
    {
        return;
    }
}

May I know how can I change the above execution to run from sync to async, without having to wait for the response before executing the next request?

Thank you.


Solution

  • To run GenerateWorkflow on a separate threadpool thread. You can call Task.Run

    Queues the specified work to run on the ThreadPool and returns a task or Task<TResult> handle for that work.

    Task.Run(() => GenerateWorkflow(...)); 
    

    If you had several requests you wanted to run concurrently, and you wanted to wait for them to all finish, you could use Task.WhenAll.

    Creates a task that will complete when all of the supplied tasks have completed.

    var task1 = Task.Run(() => GenerateWorkflow1(...)); 
    
    var task2 = Task.Run(() => SomethingElse(...)); 
    
    ...
    
    await Task.WhenAll(task1,task2,...);