ASP .NET | InvalidOperationException: An asynchronous module or handler completed while an asynchronous operation was still pending

Author - Neha Mishra
23.02.2017
|
1 Comment
|

[InvalidOperationException: An asynchronous module or handler completed while an asynchronous operation was still pending]

Error : Asp.net Web API – parent method executes itself before the child asynchronous method is completed.

Description : I have a public method that calls an asynchronous method. This asynchronous method returns void. See below :

Code :

public void mainMethod(string id) {
    asynchronousMethod(id);
    System.Diagnostics.Debug.WriteLine("This method is executed .. ");
}
protected async void asynchronousMethod(string id) {
    // Calling an external web api here that has asynchronous method and fetching some record ....

    await webapi.asyncCall(arg1, arg2);

    // await keyword is required above, else it will give compile time warning : Since this call is not awaited, execution of current method continues before the call is completed.
}

Issue : When the above mainMethod is called, before asynchronousMethod() starts, mainMethod completes itself. This gives an error as : “: An asynchronous module or handler completed while an asynchronous operation was still pending” .

Workaround : Change the return type of asynchronousMethod to Task. And await this call in the mainMethod as below :

 Task.Run(async () => { await asynchronousMethod(id); }).Wait();

Explanation : On changing return type for asynchronous method, compiler will automatically give you a message to add await to it. But this will not be sufficient. You need to explicitly wait this method so that first your mainMethod() completes this async call, then execute itself later.

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

One response on “ASP .NET | InvalidOperationException: An asynchronous module or handler completed while an asynchronous operation was still pending

  1. Raj says:

    Very helpful solution

Leave a Reply

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