gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:14:33 25 4
gpt4 key购买 nike

我有带异步操作的异步 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com