c# - 当 Controller Action 同步时,有什么理由使用异步/等待吗?

标签 c# asp.net asynchronous async-await

假设我有一个不能异步的 Controller 操作(出于各种原因),但我有一个服务(通过多种方法)使用 HttpClient 调用休息服务。使用异步客户端并使用 .Wait.Result 有什么好处吗?还是使用同步方法性能会降低?

所以要么:

//MyController.cs
public ActionResult GetSomething(int id)
{
    //lots of stuff here
    var processedResponse = _myService.Get(id);
    //lots more stuff here
    return new ContentResult(result);
}

//MyService.cs
public ProcessedResponse Get(int id)
{
    var client = new HttpClient();
    var result = client.Get(_url+id);
    return Process(result);
}

或者:

//MyController.cs
public ActionResult GetSomething(int id)
{
    //lots of stuff here
    var processedResponse = _myService.GetAsync(id).Result;
    //or, .Wait, or Task.Run(...), or something similar
    //lots more stuff here
    return new ContentResult(result);
}

//MyService.cs
public async Task<ProcessedResponse> GetAsync(int id)
{
    var client = new HttpClient();
    var result = await client.GetAsync(_url+id);
    return await Process(result);
}

最佳答案

Is there any thing to gain by using the async client and wrapping the method in Task.Run(() => _myService.Get()).Result?

您最有可能最终获得的唯一结果是僵局。想一想,你在一个线程池线程上排队一个自然异步的方法,这里 ASP.NET 已经给了你一个线程来处理你在里面的 Action。这没有多大意义。

如果您想使用异步,并且认为您实际上受益于异步提供的规模,那么您应该将您的 Controller 也重构为异步并返回一个Task<T>。 ,在那里你可以await那些异步方法。

所以我要么保持同步,要么自上而下重构代码以支持异步:

//MyController.cs
public async Task<ActionResult> GetSomethingAsync(int id)
{
    //lots of stuff here
    await GetAsync(id);
    return new ContentResult(result);
}

//MyService.cs
public async Task<ProcessedResponse> GetAsync(int id)
{
    var client = new HttpClient();
    var result = await client.GetAsync(_url+id);
    return await Process(result);
}

关于c# - 当 Controller Action 同步时,有什么理由使用异步/等待吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33913764/

相关文章:

c# - 为什么在 WCF 应用程序的 Web.config 文件中添加 httpRuntime targetFramework 可以解决与 TLS 相关的连接问题?

c# - 如何打开 NavigationController root 并传递一个值?

c# - 我的内存在哪里?重新初始化数据表

c# - AsyncPostBackTrigger 仅在第一次工作

JavaScript Promise 绕过解析并继续执行 .then()

c# - 显示 GroupBy ASP.NET MVC 的第一个实例和最后一个实例

c# - 从 ASP.Net 中的 ascx 页面抓取控件

asp.net - ASP.NET MVC 中的完全自定义身份验证 : losing HttpContext. 用户

c# - 任务类无法获取正确的值

scala - 如何从单个枚举器中生成多个枚举器(分区、拆分……)