【发布时间】:2016-02-09 11:32:00
【问题描述】:
我有带有异步操作的异步控制器。在操作中,我在 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);
}
}
【问题讨论】:
-
async 并不是说不需要16秒,而是需要16秒
-
那么当我们调用单个 WCF 方法时,使用 async 的优势在哪里?
-
异步只需确保您的线程已释放到应用程序池中,当操作完成时,它会再次从池中选择线程并开始执行下一个
-
你能给我举个例子,使用异步控制器和动作更有意义吗?
-
AsyncController已弃用。您只需在方法上使用async Task<string>即可使其异步。
标签: c# asp.net-mvc asynchronous