问题描述
我遇到了GetAsync的问题,正如该主题所建议的那样,尽管在挂起之前工作良好,但是在执行了几个小时后挂起了。
该程序是一个netcore3.1 worker服务,在Windows Server 2019上作为Windows服务运行,但是当我在本地开发机上将其作为直接控制台应用程序运行时,也会出现问题。这是一个非常基本的服务,在取消令牌未取消的情况下循环,然后在请求之间休眠几秒钟,然后将解析的数据移至数据库。它不是特别忙碌,并且平均每5秒可能向返回JSON的rest API发出1个请求。 http代码如下:
public static async Task<T> GetAsync<T>(this HttpClient httpClient,bool useStreams,string url,CancellationToken cancellation = default) where T : class
{
HttpCompletionOption option = useStreams == true ? HttpCompletionOption.ResponseHeadersRead : HttpCompletionOption.ResponseContentRead;
_Logger.Debug($"Making GET request - {option},{url}");
using (HttpResponseMessage response = await httpClient.GetAsync(url,option,cancellation).ConfigureAwait(false))
{
// check success of request
if (response.IsSuccessStatusCode == true)
{
_Logger.Debug($"Reading GET contents - {option},{url}");
return await _ReadContents<T>(response,useStreams,cancellation).ConfigureAwait(false);
}
else
{
// log out any relevant content
string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
_Logger.Error($"GET Request failed: {option},{url},{content}");
throw new HttpRequestException(response.StatusCode.ToString());
}
}
}
private static async Task<T> _ReadContents<T>(HttpResponseMessage response,CancellationToken cancellation = default) where T : class
{
if (useStreams == true)
{
using (Stream stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
{
return await JsonSerializer.DeserializeAsync<T>(stream,cancellationToken: cancellation).ConfigureAwait(false);
}
}
else
{
string content = null;
try
{
content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return JsonSerializer.Deserialize<T>(content);
}
catch (JsonException)
{
// dump out json
_Logger.Error($"Error parsing: {content}");
throw;
}
}
}
HttpClient的创建如下:
var httpClientHandler = new HttpClientHandler
{
UseProxy = false,AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,CookieContainer = new CookieContainer(),UseCookies = true,};
if (string.IsNullOrWhiteSpace(m_ProxyAddress) == false)
{
_Logger.Debug($"Using proxy {m_ProxyAddress}");
httpClientHandler.Proxy = new WebProxy(m_ProxyAddress,false,null,new NetworkCredential(m_ProxyUsername,m_ProxyPassword));
httpClientHandler.UseProxy = true;
}
m_HttpClient = new HttpClient(httpClientHandler);
m_HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
m_HttpClient.DefaultRequestHeaders.Add("User-Agent","appAgent");
m_HttpClient.Timeout = TimeSpan.FromSeconds(10);
日志文件中的最后一件事是“进行GET请求xxxx”,因此我知道它挂在GetAsync上。在主循环中,我正确使用了“等待”(即未使用任何阻塞调用,如GetAwaiter()。GetResult()或.Result。
无论useStreams是true还是false,它都将挂起。无论是否使用代理,它都会挂起。我尝试拆掉HttpClient并每小时在计时器上重新创建它,但这没有帮助。
我不知道还有什么可以尝试的,我已经读过很多关于该主题的类似文章,但没有一个与此完全相同,而且我的想法已经用完了。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)