I have a piece of code for downloading content from a webpage, as follows:
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)
{
...
}
}
}
Notice that I have one readonly instance of the HttpClient class. I have a single instance of Downloader
for my application. Is the initialization of HttpClient shown above, a more efficient way to initialize HttpClient than creating an instance per call to GetContent, as follows:
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)
{
...
}
}
}
Thanks in advance for advice!
Note: I'm not interested in HttpClientFactory
for this example, or dependency injection.