Skip to main content
 首页 » 编程设计

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

2024年02月05日12jyk

我有带异步操作的异步 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(); 
}