【问题标题】:How to execute async 'fire and forget' operation in ASP.NET Web API [duplicate]如何在 ASP.NET Web API 中执行异步“即发即弃”操作 [重复]
【发布时间】:2013-11-23 23:38:41
【问题描述】:

所以,我有这个 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.

请问我怎样才能做到这一点??

谢谢

【问题讨论】:

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


【解决方案1】:

你要求做的是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 队列),并让一个独立的服务(例如 Azure Worker Role)处理该队列。

【讨论】:

    猜你喜欢
    • 2019-02-09
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多