2017-08-12 162 views
-2

我已经有一段时间了,我尝试在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列表,任何人都可以帮我吗?如果有人能告诉我如何正确书写,我会很高兴。

+3

执行时间为什么应该是同步和异步有什么不同?执行的代码量相同,特别是如果您没有运行任何其他代码。 – jdweng

+3

对于'myHttpCall'方法也没有任何异步,你不会在里面等待任何东西。 – DavidG

+2

事实上,你应该得到一个关于异步方法的警告,不要等待... –

回答

2

您的HTTP调用是同步的。在myHttpCall方法使用HttpClient的或多或少是这样的:

private async Task<string> myHttpCall(string path) 
{ 
    using(HttpClient client = new HttpClient()) 
    { 
      HttpResponseMessage response = await client.GetAsync(path); 
      return await response.Content.ReadAsStringAsync(); 
    } 
} 

编辑:自动解压通下列对象添加到HttpClient构造:

HttpClientHandler handler = new HttpClientHandler() 
{ 
    AutomaticDecompression = DecompressionMethods.GZip 
}; 
+3

虽然肯定不明显,但“HttpClient”意味着每次都要重复使用,而不是创建和处理。我们应该尝试摆脱用'HttpClient'推荐这种模式的习惯。 – Crowcoder

+0

有趣的是,我不知道它。更多细节[here](https://stackoverflow.com/questions/15705092/do-httpclient-and-httpclienthandler-have-to-be-disposed) – Kedrzu