【问题标题】:HttpClient Poor PerformanceHttpClient 性能不佳
【发布时间】:2022-01-13 14:10:58
【问题描述】:

当我在每个请求上创建一个新的 HttpClient 对象时,我得到了 很快就得到了回应。

我知道我们不应该在每个请求上创建一个新的HttpClient,因此我开始使用HttpClientFactory 中的HttpClient 并在每个请求上注入HttpClient,但令人惊讶的是性能非常糟糕。

Global.asax

var services = new ServiceCollection();
services.AddHttpClient();
builder.Populate(services);

var autofacContainer = builder.Build();

Sample.asmx

方法 1:响应时间为 1.5 秒

var client_ = DependencyInjector.Provider.RequestLifetime.Resolve<HttpClient>();;//Inject
using (var request_ = new System.Net.Http.HttpRequestMessage())
            {
var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

方法 2:响应时间为 0.5 秒

var client_ = new HttpClient();
using (var request_ = new System.Net.Http.HttpRequestMessage())
            {
var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

使用 .Network 4.8。有什么建议吗?

【问题讨论】:

  • 当您分析代码时,哪一行花费了额外的时间?您的 DI 调用很可能是缓慢的部分。 (也是an anti-pattern:只要有可能,依赖项应该被注入到控制器或方法中,而不是显式地从服务定位器中获取。)
  • SendAsync 需要时间。由于我使用的是 asp.net 旧 ASMX,因此我没有选择从构造函数注入依赖项。

标签: c# dotnet-httpclient .net-framework-4.8


【解决方案1】:

我开始在空白项目中一一移动我的代码,我找到了根本原因。只是分享以防有人遇到类似问题。

我使用 SumoLogic.Logging.Serilog sink 在 Sumo Logic 中发送日志数据,我的实现或这个包似乎有问题,但在从 Program.cs 删除下面的代码行后,它工作得更好

loggerConfig.WriteTo.SumoLogic(endpointUrl: new Uri(sumoLogicUri));

为了解决问题,我按照docs 中的建议更改了扩展方法

    loggerConfig.WriteTo.BufferedSumoLogic(endpointUrl: new Uri(sumoLogicUri));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    • 2016-11-06
    • 2019-06-15
    • 2013-06-11
    • 2010-12-31
    • 2012-01-25
    • 2021-12-15
    相关资源
    最近更新 更多