如何使ASP.NET Core Web API操作异步执行? [英] How to make ASP.NET Core Web API action execute asynchronously?

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

问题描述

我在ASP.NET Core Web API的控制器中有一个可上载和处理文件的操作.文件较小时可以,但是如果文件较大该怎么办?我希望该操作异步执行,因此我将方法定义为 async ,其返回值只是可以等待的 Task ,并在 await Task中插入了连续的操作.Run(()=> ...)块,使动作也 async 并使用 await 关键字调用此方法,但实际上,调用此方法后,动作不会返回.我尝试上传大文件,不得不等到文件完全上传并处理完毕.那么,我该怎么做才能使该操作真正异步执行?

I have an action in controller in my ASP.NET Core Web API that uploads and processes a file. It's okay when file is small, but what if the file will be large? I want this action to execute asynchronously, so I defined method as async, its return value is just Task to be awaitable, and inserted continuous operations in await Task.Run(() => ...) blocks, made the action also async and call this method with await keyword, but, in fact, this action doesn't return after calling this method. I've tried to upload large file, and have had to wait until file is completely uploaded and processed. So, what should I do to make this action executed really asynchronously?

推荐答案

Web Api项目的调用方不了解C#详细信息, Task 是什么或 await 表示.可能是C#或JS,甚至是PHP,或者是在浏览器栏中键入您的URL的人.

The calling side of your Web Api project has no idea of C# details, of what a Task is or await means. It might be C# or JS or even PHP or a person that typed your URL in a browser bar.

默认情况下(并且应该!),您的Web Api将等待直到整个处理完成,然后发出成功的信号.通常,这是通过状态码作为返回值来完成的.

Your Web Api will by default (and should!) wait until the whole processing is done and then give a signal that is was successful. This is generally done through a status code as return value.

现在,客户端正在调用,您的API不必等待.但这是客户端编程.您实际上无法在API中做任何事情来解决客户端的问题.

Now the client calling your API does not have to be stuck waiting for that. But that's client side programming. You cannot really do anything in your API to solve the client's problem with that.

否则,您可以使您的API只是将文件放入处理队列中,以便稍后由其他软件进行处理.但这将需要另一种体系结构,因为现在当不再与API连接时,需要将失败(或一般情况下)的成功通知给调用方,因此您需要回调.

Otherwise, you could make your API just put the file in a processing queue to be processed by a different piece of software later. But that would need another architecture, because now the caller needs to be notified of success of failure (or result in general) when it's not longer connected to your API, so you'd need callbacks.

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

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