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

|
| By Webner
[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.

One comment

Leave a Reply

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