HttpClient best practice in .Net core
We use httpclient widely in application to make connections to another external API to get data from c# code.
But it is required to see what impact is if we use this httpclient in bad way. There will be performance issues in application if we used in below way.
Consider code below C# code
Console.WriteLine(“Starting connections”);
for(int i = 0; i<100; i++)
{
using(var client = new HttpClient())
{
var result = await client.GetAsync(“http://google.com");
Console.WriteLine(result.StatusCode);
}
}
Output like below
We can use using statements for classes those implements IDisposable
In this case HttpClient
, goes out of scope and is disposed. The dispose
method is called and whatever resources are in use are cleaned up. This is a very typical pattern in .NET and we use it for everything from database connections to stream writers.
All unmanaged code will be cleaned once using block is out of scope.
But with HttpClient
case is different and have some problems here.