8

So, I have this Web API action, that executes an asynchronous function.

public void Post([FromBody]InsertRequest request)
{
    InsertPostCommand.Execute(request);
    DoAsync();
}

private async void DoAsync()
{
    await Task.Run(() =>
    {
        //do async stuff here
    });
}

I actually want the controller action to return to the client whilst the async operation executes.

I did this and I am getting an exception thus:

System.InvalidOperationException: An asynchronous module or handler completed while an asynchronous operation was still pending.

How can I achieve this please ??

Thanks

Code Maverick
  • 20,171
  • 12
  • 62
  • 114
sacretruth
  • 780
  • 2
  • 18
  • 34
  • 1
    http://stackoverflow.com/questions/17659603/async-void-asp-net-and-count-of-outstanding-operations – dcastro Nov 12 '13 at 00:42
  • A good question. But read carefully all the answers provided. Multithreading is tricky in ASP.NET. – Agat Nov 12 '13 at 01:13

1 Answers1

14

What you are asking to do is extremely dangerous. I have a blog post that explains why this is a bad idea, including code for a BackgroundTaskManager type that minimizes the chance that something will go horribly wrong. Unfortunately, even when you register your background work with the ASP.NET runtime, it's still a bad idea to depend on this behavior.

The proper solution is to have your WebAPI request place a request into a reliable queue (such as Azure Queue), and have an independent service (such as an Azure Worker Role) process that queue.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810