如何在ASP.NET Web API中执行异步“即发即忘”操作

时间:2013-11-12 00:29:09

标签: c# asp.net asynchronous asp.net-web-api

所以,我有这个Web API动作,它执行一个异步函数。

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

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

我实际上希望控制器操作在执行异步操作时返回到客户端。

我这样做了,因此我得到了例外:

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

我怎样才能做到这一点?

由于

1 个答案:

答案 0 :(得分:14)

你要做的是extremely dangerous。我有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。不幸的是,即使您在ASP.NET运行时注册后台工作,依赖此行为仍然是一个坏主意。

正确的解决方案是让您的WebAPI请求将请求放入可靠的队列(例如Azure Queue),并拥有一个排队的独立服务(例如Azure辅助角色)进程。