[英]Any issue if no await on HttpClient().GetAsync().Result.Content.ReadAsStringAsync().Result?
Any issue with this C# method (.Net Framework 4.8) with not having await?这个 C# 方法(.Net Framework 4.8)没有等待有什么问题吗? I am using ReadAsStringAsync() with no await.
我正在使用 ReadAsStringAsync() 没有等待。 Caller of RetrieveContent() method can't call it asynchronously.
RetrieveContent() 方法的调用者不能异步调用它。 So, I need to avoid making it async method.
所以,我需要避免使它成为异步方法。 This is a Windows Console app that can also be installed as a Windows Service- with an endpoint listening for requests.
这是一个 Windows 控制台应用程序,也可以作为 Windows 服务安装 - 端点侦听请求。 It is supposed to do Synchronous processing- one request at a time.
它应该进行同步处理——一次一个请求。
public string RetrieveContent()
{
return new HttpClient().GetAsync("https://www.google.com").Result.Content.ReadAsStringAsync().Result;
}
OR或者
public string RetrieveContent()
{
var response = new HttpClient().GetAsync("https://www.google.com").Result;
return response.Content.ReadAsStringAsync().Result;
}
Updates: I can change like this.更新:我可以这样改变。 Thus, caller to this method doesn't need an information from Async method.
因此,此方法的调用者不需要来自 Async 方法的信息。 Will this cause a dead-lock too?
这也会导致死锁吗?
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} ");
}
'''
Calling Result
from synchronous code blocks is considered unsafe and may cause deadlocks because the task might depend on other incomplete tasks.从同步代码块调用
Result
被认为是不安全的,并且可能导致死锁,因为该任务可能依赖于其他未完成的任务。 Instead, you should usually be striving to make caller methods async as much as possible.相反,您通常应该努力使调用方方法尽可能异步。 In this specific case, however, it may be okay with a
Task.Run
wrapper.但是,在这种特定情况下,使用
Task.Run
包装器可能没问题。
See this question for more details: What's the "right way" to use HttpClient synchronously?有关更多详细信息,请参阅此问题: 同步使用 HttpClient 的“正确方法”是什么?
Math.Floor.数学楼。 If it doesnt work try to sort the array!
如果它不起作用,请尝试对数组进行排序! Silly beginner mistake!
愚蠢的初学者错误!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.