我已经有一段时间了,我尝试在C#中编写异步代码,我做了它,并确定它是异步的,最近我读了我检查邮递员函数完成异步时间和同步时间,看起来好像需要完全相同的时间,我在代码中做了什么错误?即使我用async/await编写异步操作也不起作用 - C#
这里是我的代码:
[HttpGet]
[Route("customerslist")]
public async Task<IHttpActionResult> getData()
{
string url1 = @"https://jsonplaceholder.typicode.com/photos";
string url2 = @"https://jsonplaceholder.typicode.com/comments";
string url3 = @"https://jsonplaceholder.typicode.com/todos";
Task<string> firstTask = myHttpCall(url1);
Task<string> secondTask = myHttpCall(url2);
Task<string> thirdTask = myHttpCall(url3);
await Task.WhenAll(firstTask, secondTask, thirdTask);
var result = firstTask.Result + secondTask.Result + thirdTask.Result;
return Ok(result);
}
private async Task<string> myHttpCall(string path)
{
string html = string.Empty;
string url = path;
// Simple http call to another URL to receive JSON lists.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}
return html;
}
我做的HTTP请求到另一个URL得到他们的JSON列表,任何人都可以帮我吗?如果有人能告诉我如何正确书写,我会很高兴。
执行时间为什么应该是同步和异步有什么不同?执行的代码量相同,特别是如果您没有运行任何其他代码。 – jdweng
对于'myHttpCall'方法也没有任何异步,你不会在里面等待任何东西。 – DavidG
事实上,你应该得到一个关于异步方法的警告,不要等待... –