如何管理最大连接数,HttpClient,C#?

时间:2018-07-18 06:32:54

标签: c# windows-services httpclient connection-pooling

我正在使用Windows服务。 Windows服务的代码非常简单,但是方式却很奇怪!
在Windows服务中,我应该每20秒调用一次WebApi并将结果保存到SQL数据库中
我正在使用autofacHttpClient上创建Program.cs的实例

// HttpClient
builder.Register(ctx =>
{
    var httpClient = new HttpClient
    {
        BaseAddress = new Uri(StaticAssets.WebApiBaseAddress)
    };
    httpClient.DefaultRequestHeaders.Accept.Clear();
    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    return httpClient;
});

我从不手动处置httpClient实例。
在运行Windows服务大约8个小时后,IIS无法正常工作,我们无法再远程访问服务器,我们测试了Windows远程桌面连接,VNC(服务器上有VNC)...
我们可以使用KVM远程访问服务器并停止Windows服务,然后一切都会恢复。 我从here中发现问题是由于连接号!我不确定吗?
我也发现了以下内容:

<system.web>
 <processModel maxWorkerThreads="100" maxIoThreads="100" minWorkerThreads="50"/>
 <httpRuntime minFreeThreads="704" minLocalRequestFreeThreads="608"/>
</system.web>

<system.net>
 <connectionManagement>
  <add address="[ProvideIPHere]" maxconnection="96"/>
 </connectionManagement>
</system.net>

来自https://support.microsoft.com/en-us/help/821268/contention-poor-performance-and-deadlocks-when-you-make-calls-to-web-s

HttpClient .Net Windows服务和IIS中管理最大连接的最佳实践是什么?

1 个答案:

答案 0 :(得分:0)

基于谷歌搜索的解决方案:

1。将HttpClient定义为SingleTone,请勿手动进行处理。
AutoFac中,使用类似以下的内容:

builder.Register(ctx =>
{
    var httpClient = new HttpClient
    {
        BaseAddress = new Uri('https://www.sample.com/')
    };
    httpClient.DefaultRequestHeaders.Accept.Clear();
    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    return httpClient;
}).SingleInstance();

.Net Core中,使用以下命令:

services.AddSingleton(provider =>
{
    var httpClient = new HttpClient
    {
        BaseAddress = new Uri('https://www.sample.com/')
    };
    httpClient.DefaultRequestHeaders.Accept.Clear();
    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    return httpClient;
});

2。在您的config文件中添加以下内容

<configuration>
    ....
    <system.web>
     <processModel maxWorkerThreads="100" maxIoThreads="100" minWorkerThreads="50"/>
     <httpRuntime minFreeThreads="704" minLocalRequestFreeThreads="608"/>
    </system.web>

    <system.net>
     <connectionManagement>
      <add address="[ProvideIPHere]" maxconnection="96"/>
     </connectionManagement>
    </system.net>
</configuration>