C#高效使用HttpClient
C# efficient use of HttpClient
我有一段从网页下载内容的代码,如下:
public class Downloader
{
private readonly HttpClient _client = new HttpClient();
public async Task<(HttpStatusCode, string)> GetContent(Uri site)
{
HttpStatusCode status = HttpStatusCode.Unused;
try
{
var response = await _client.GetAsync(site);
status = response.StatusCode;
var content = await response.Content.ReadAsStringAsync();
return (status, content);
}
catch (Exception e)
{
...
}
}
}
请注意,我有一个 HttpClient class 的只读实例。我的应用程序只有一个 Downloader
实例。就是上面展示的HttpClient的初始化,比每次调用GetContent创建一个实例更高效的初始化HttpClient的方式,如下:
public class Downloader
{
public async Task<(HttpStatusCode, string)> GetContent(Uri site)
{
HttpStatusCode status = HttpStatusCode.Unused;
try
{
using var client = new HttpClient();
var response = await client.GetAsync(site);
status = response.StatusCode;
var content = await response.Content.ReadAsStringAsync();
return (status, content);
}
catch (Exception e)
{
...
}
}
}
在此先感谢您的建议!
注意:对于此示例或依赖项注入,我对 HttpClientFactory
不感兴趣。
静态HttpClient
(或单例上的实例字段,本质上是同一件事)是proper way to go for modern versions of .NET Core. The SocketsHttpHandler
in .NET Core 2.1 and newer handles the DNS problems inherent in the singleton HttpClient
approach。
我有一段从网页下载内容的代码,如下:
public class Downloader
{
private readonly HttpClient _client = new HttpClient();
public async Task<(HttpStatusCode, string)> GetContent(Uri site)
{
HttpStatusCode status = HttpStatusCode.Unused;
try
{
var response = await _client.GetAsync(site);
status = response.StatusCode;
var content = await response.Content.ReadAsStringAsync();
return (status, content);
}
catch (Exception e)
{
...
}
}
}
请注意,我有一个 HttpClient class 的只读实例。我的应用程序只有一个 Downloader
实例。就是上面展示的HttpClient的初始化,比每次调用GetContent创建一个实例更高效的初始化HttpClient的方式,如下:
public class Downloader
{
public async Task<(HttpStatusCode, string)> GetContent(Uri site)
{
HttpStatusCode status = HttpStatusCode.Unused;
try
{
using var client = new HttpClient();
var response = await client.GetAsync(site);
status = response.StatusCode;
var content = await response.Content.ReadAsStringAsync();
return (status, content);
}
catch (Exception e)
{
...
}
}
}
在此先感谢您的建议!
注意:对于此示例或依赖项注入,我对 HttpClientFactory
不感兴趣。
静态HttpClient
(或单例上的实例字段,本质上是同一件事)是proper way to go for modern versions of .NET Core. The SocketsHttpHandler
in .NET Core 2.1 and newer handles the DNS problems inherent in the singleton HttpClient
approach。