问题描述
所以,我有此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 ??
感谢
推荐答案
你所要求做的是extremely危险。我有一个的几率降至最低。不幸的是,即使你注册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的工作者角色)的排队过程。
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操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!