我正在对一些已经编写的旧代码进行自我回顾,并想知道下面的代码是否以任何方式阻止了当前线程,还是一直没有阻塞?
按照Microsoft的建议,对于所有应用程序,我都使用单个HttpClient实例。
HttpClient打算实例化一次,并在应用程序的整个生命周期中重新使用。为每个请求实例化一个HttpClient类将耗尽重载下可用的套接字数。这将导致SocketException错误.https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.8#remarks
public virtual async Task<Tuple<string, bool>> PostAsync(string resourceUrl, string body, string basicToken)
{
string methodName = "PostAsync";
var response = new Tuple<string, bool>(string.Empty, false);
try
{
var content = new StringContent(body, Encoding.UTF8, "application/json");
var request = new HttpRequestMessage(HttpMethod.Post, resourceUrl);
request.Headers.Add("Authorization", basicToken);
request.Content = new StringContent(body, Encoding.UTF8, "application/json");
var httpResponse = await ApplicationWrapper.AccessTokenClient.SendAsync(request).ConfigureAwait(false);
response = new Tuple<string, bool>(await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), httpResponse.IsSuccessStatusCode);
}
catch (WebException e)
{
Util.Log(methodName + " | WebException: " + e.Message + "|" + e.StackTrace.ToString());
using (WebResponse WebResponse = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)WebResponse;
using (var streamReader = new StreamReader(WebResponse.GetResponseStream()))
Util.Log(methodName + " | Exception postAsync API: " + streamReader.ReadToEnd());
}
}
catch (Exception ex)
{
Util.Log(methodName + " | Exception: " + ex.Message + "|" + ex.StackTrace.ToString() + "|" + ex.InnerException);
}
return response;
}微软为ReadAsStringAsync声明的事实
此外,为了避免死锁,建议使用ConfigureAwait(false)
ConfigureAwait(false)配置任务,以便在等待之后继续在调用方上下文中运行,从而避免任何可能的死锁。https://medium.com/bynder-tech/c-why-you-should-use-configureawait-false-in-your-library-code-d7837dce3d7f
在压力下阻塞异步代码会影响服务器的CPU利用率,随着线程数量的不断增加,服务器利用率将达到90% .在上述代码中是否有阻塞的方面?
发布于 2019-12-27 13:39:57
这一切在我看来都很好。一个简单的经验法则是,如果您看到异步方法的返回值( .Result )上出现了任何.Wait()或Task,那么您就阻塞了可能应该在await的位置。没有在这里看到-你似乎在等待所有异步调用。现在,只需确保调用此方法的任何内容都是awaiting,一直到调用堆栈。如果你挡住了任何地方,这都是徒劳的。:)
https://stackoverflow.com/questions/59498057
复制相似问题