如何在 ASP.NET Web API 中执行异步“即发即忘"操作 [英] How to execute async 'fire and forget' operation in ASP.NET Web API

查看:25
本文介绍了如何在 ASP.NET Web API 中执行异步“即发即忘"操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 ??

谢谢

推荐答案

你要求做的是 极其危险.我有一篇博客文章解释了为什么这是一个坏主意,包括用于BackgroundTaskManager 类型,最大限度地减少出现可怕错误的可能性.不幸的是,即使您使用 ASP.NET 运行时注册您的后台工作,依赖这种行为仍然是一个坏主意.

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.

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

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.

这篇关于如何在 ASP.NET Web API 中执行异步“即发即忘"操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆