c# .net 6.0 windows 服务 - httpclient 在一段时间后调用抛出超时异常

问题描述 投票:0回答:1

我有一个 .Net 6.0 windows 服务,每隔几秒就会向 api 发送数据。 Windows服务在一段时间内工作正常。然而,过了一会儿,也许 24 小时后,它突然开始记录超时异常,并继续这样做。要解决这个问题,我必须重新启动 Windows 服务。

这是我调用 API 的代码

private static HttpClient client = new HttpClient(); 
        
        public static void SetTimeout(int timeout, int poolConnectionLifeTime)
        {
            var handler = new SocketsHttpHandler
            {
                PooledConnectionLifetime = TimeSpan.FromMinutes(poolConnectionLifeTime) 
            };
            client = new HttpClient(handler);
            client.Timeout = TimeSpan.FromSeconds(timeout);
            TokenRetriever.Log.Info("Auth API http client initialised");
        }      

        public async Task<string> ExecuteGetAndReturnResponse(Dictionary<string, string> requestParams, string url)
        {
            string responseReturned = string.Empty;

            try
            {

                using (var response = await client.PostAsync(url, new FormUrlEncodedContent(requestParams)))
                {
                    if (response.IsSuccessStatusCode)
                    {
                       
                        using (var stream = await response.Content.ReadAsStreamAsync())
                        {
                            using (var streamReader = new StreamReader(stream))
                            {
                                responseReturned = await streamReader.ReadToEndAsync();
                               
                            }
                        }
                    }
                    else
                    {
                        responseReturned = $"ERROR: - {response.StatusCode} - {response.ReasonPhrase}";
                        TokenRetriever.Log.Info($"Response returned {responseReturned}");
                    }

                }
            }
            catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException)
            {
               TokenRetriever.Log.Error("Fetching token Timed out: " + ex.Message);
            }
            catch (TaskCanceledException ex)
            {
                // Handle cancellation.
               TokenRetriever.Log.Error("Task Cancellation fetching token error: " + ex.Message);
            }

            return responseReturned;
        }

我尝试将 PooledConnectionLifetime 设置为 2 分钟(可配置)。 我还覆盖了默认的 100 秒超时(可配置)。 Windows 服务调用 3 个不同的 API(3 个独立的类)——每个都有自己的静态 httpclient 实例。 我的想法用完了 - 任何建议

c# windows-services httpclient
1个回答
0
投票

尝试将

static HttpClient
的实例化更改为以下

private static HttpClient client = HttpClientFactory.Create(new SocketsHttpHandler
            {
                PooledConnectionLifetime = TimeSpan.FromMinutes(poolConnectionLifeTime) 
            }); 

如果您从 Program.cs 调用

SetTimeout
(我不确定您在那里做什么),那么这些更改将不会应用到此类中,因为您正在使用默认的
HttpClient
创建一个新的
SocketsHttpHandler
对象。

© www.soinside.com 2019 - 2024. All rights reserved.