c# - 具有异步操作的异步 Controller 不起作用

标签 c# asp.net-mvc asynchronous

我有带异步操作的异步 Controller 。在操作中,我在 SomeMethodOne 中调用 WCF 服务方法(返回结果需要 10 秒),然后在 SomeMethodTwo 中执行一些数学运算(在我的计算机上执行大约 6 秒)。据我所知,在等待 WCF 服务方法的结果期间,我的计算机应该执行 SomeMethodTwo 但它没有执行,所有代码执行 10 秒 + 6 秒 = 16 秒。为什么?

public class TestController : AsyncController
{
    public async Task<ActionResult> Index()
    {
        string result =  await SomeMethodOne();

        SomeMethodTwo();

        return View();
    }

    private async Task<string> SomeMethodOne() // it needs 10 seconds to return result from WCF service
    {
        using (Service1Client client = new Service1Client())
        {
            return await client.GetDataAsync(5);
        }
    }

    private void SomeMethodTwo() // it executes about 6 seconds on my computer
    {
        double result = 0;
        for (int i = 0; i < 1000000000; i++)
        {
            result += Math.Sqrt(i);
        }
    }
}

我在本地运行的 WCF 服务:

public class Service1 : IService1
{
    public string GetData(int value)
    {
        Thread.Sleep(10000);
        return string.Format("You entered: {0}", value);
    }        
}

最佳答案

您的问题是您正在立即使用 await:

string result =  await SomeMethodOne();

await 表示您的 Controller 操作将在继续执行之前“异步等待”(await) SomeMethodOne 的结果。

如果你想做异步并发,那就不要马上await。相反,您可以通过调用方法开始异步操作,然后稍后调用 await:

public async Task<ActionResult> Index()
{
  Task<string> firstOperation = SomeMethodOne();

  SomeMethodTwo();

  string result = await firstOperation;

  return View();
}

关于c# - 具有异步操作的异步 Controller 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35290977/

相关文章:

asp.net-mvc - 如何在 App_Code 文件夹中的 Razor View 中使用 Url.Action

c# - 用于动态 View 数据/表单的 ASP.Net MVC 编辑器模板

c++ - std::async 将创建和异步执行的最大线程数是多少?

c# - 使用 StructureMap.DependencyInjection 在 C# dotnet core 2.0 中简单代理类依赖注入(inject)

c# - 在 Entity Framework Core 的不同方法中使用相同的事务

c# - 如何使用 UnitsNet nuget 包中的 Parse() 方法

c# - 使用 LINQ 枚举的正确方法是什么?

.net - 无区域 Controller 的子文件夹

javascript - Node.js:异步代码 + js 闭包的问题

java - 如何使用异步套接字?