c# - MVC 异步 Controller Action

标签 c# asp.net-mvc asp.net-mvc-4 asynchronous .net-core

<分区>

假设我们在标准 mvc Controller 中有以下两个方法。

public class SomeController : Controller
{
    public async Task<Response> SomeAction1()
        => await _someService.SomeAsyncMethod();

    public Task<Response> SomeAction2()
        => _someService.SomeAsyncMethod();

    // SomeAsyncMethod might look like this.
    // public async Task<Response> SomeAsyncMethod()
    //    => await someDbAction();
}

简单的问题: Controller 基类是否执行等待/异步任务?

或者这两个 Action 做完全相同的事情吗?

-- 编辑以澄清一点。 --

https://learn.microsoft.com/en-us/aspnet/mvc/overview/performance/using-asynchronous-methods-in-aspnet-mvc-4

How Requests Are Processed by the Thread Pool

On the web server, the .NET Framework maintains a pool of threads that are used to service ASP.NET requests. When a request arrives, a thread from the pool is dispatched to process that request. If the request is processed synchronously, the thread that processes the request is busy while the request is being processed, and that thread cannot service another request.

我的目标是了解返回任务的方法是否需要伴随单词 async。如果关键字不存在,即使 SomeAsyncMethod 中有一个 await 创建回调,它是否会将方法视为同步并保持线程?

最佳答案

do both of these actions do the exact same thing?

完全。虽然两者的作用是一样的。每当您将方法标记为 async 时并且有一个或多个await方法体中的表达式,编译器将生成一个状态机,用于在 await 之后异步恢复方法。打电话。

但是,由于方法主体是返回 Task<Action> 的单个方法调用,所有编译器机制都没有用,并返回 Task直接将导致更小的编译代码。

在运行时,您可能不会注意到差异,除了 async Task<Action> 的执行时间可能略长。案例。

关于c# - MVC 异步 Controller Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42103269/

相关文章:

c# - 如何实时跟踪 Twitter feed?

c# - asp.net mvc 4,线程被模型绑定(bind)改变了吗?

c# - 如何检测证书的类型(A1 或 A3)?

c# - 图像转换

c# - 悬停鼠标时如何在 gridview 中缩放照片?

asp.net-mvc - 没有布局的 Razor View

c# - 异步调用 - 如何在 UI 线程上等待它们

asp.net-mvc-4 - MVC SiteMap - 当不同节点指向相同操作时 SiteMap.CurrentNode 未映射到正确的路线

c# - 如何更改 MVC4 网站的 url?

c# - 通用列表到 EntitySet 的转换