hi i read this article You're using HttpClient wrong and it is destabilizing your software the article is suggesting these 2
- Make your HttpClient static
- Do not dispose of or wrap your HttpClient in a using unless you explicitly are looking for a particular behaviour (such as causing your services to fail)
now a newbie on c# like me would just follow it like the code posted on the article here is the original code the he said would make the application fail
using System;
using System.Net.Http;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Starting connections");
for(int i = 0; i<10; i++)
{
using(var client = new HttpClient())
{
var result = client.GetAsync("http://aspnetmonsters.com").Result;
Console.WriteLine(result.StatusCode);
}
}
Console.WriteLine("Connections done");
}
}
}
and to fix it he gave this code:
using System;
using System.Net.Http;
namespace ConsoleApplication
{
public class Program
{
private static HttpClient Client = new HttpClient();
public static void Main(string[] args)
{
Console.WriteLine("Starting connections");
for(int i = 0; i<10; i++)
{
var result = Client.GetAsync("http://aspnetmonsters.com").Result;
Console.WriteLine(result.StatusCode);
}
Console.WriteLine("Connections done");
Console.ReadLine();
}
}
}
now being curious like any newbie i thought of the for loop inside the using statement will the effect be the same as the latter?
thank you
usingstatement will allow for the reuse of the client though not static for the life time of the main method.