簡體   English   中英

如果沒有等待 HttpClient().GetAsync().Result.Content.ReadAsStringAsync().Result 有什么問題嗎?

[英]Any issue if no await on HttpClient().GetAsync().Result.Content.ReadAsStringAsync().Result?

這個 C# 方法(.Net Framework 4.8)沒有等待有什么問題嗎? 我正在使用 ReadAsStringAsync() 沒有等待。 RetrieveContent() 方法的調用者不能異步調用它。 所以,我需要避免使它成為異步方法。 這是一個 Windows 控制台應用程序,也可以作為 Windows 服務安裝 - 端點偵聽請求。 它應該進行同步處理——一次一個請求。

public string RetrieveContent()
{
  return new HttpClient().GetAsync("https://www.google.com").Result.Content.ReadAsStringAsync().Result;
}

或者

public string RetrieveContent()
{
  var response = new HttpClient().GetAsync("https://www.google.com").Result;
  return response.Content.ReadAsStringAsync().Result;
}

更新:我可以這樣改變。 因此,此方法的調用者不需要來自 Async 方法的信息。 這也會導致死鎖嗎?

public void RetrieveContent()  //this is just logging content
{
  var response = new HttpClient().GetAsync("https://www.google.com").Result;

  if (response.StatusCode == HttpStatusCode.OK)
    _logger.LogInformation($"content: {response.Content.ReadAsStringAsync().Result} ");  //_logger is logging to local disk I/O
  else 
    _logger.LogError($"HttpStatusCode: {response.StatusCode} ");
}
'''

從同步代碼塊調用Result被認為是不安全的,並且可能導致死鎖,因為該任務可能依賴於其他未完成的任務。 相反,您通常應該努力使調用方方法盡可能異步。 但是,在這種特定情況下,使用Task.Run包裝器可能沒問題。

有關更多詳細信息,請參閱此問題: 同步使用 HttpClient 的“正確方法”是什么?

數學樓。 如果它不起作用,請嘗試對數組進行排序! 愚蠢的初學者錯誤!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM