When using Microsoft HttpClient, Microsoft httpclient cannot be used.
Recently, the company has been increasingly using webapis. Which of the following is the Api client tool we use? The most common estimation is HttpClient. In the Microsoft class library, the namespace address is System. net. http is an SDK framework that supports asynchronous programming APIs. When I was developing a project in the company, I checked some information about how to use this Client more rationally, the biggest guarantee is to withstand high-frequency client-initiated connections and thread security. Next I will briefly explain how to use them properly.
I. Common scenarios (It's a pitfall)
First look at the Code:
1 while (true)2 {3 using (HttpClient client = new HttpClient())4 {5 var result = client.GetStringAsync("http://www.xxxxx.com").Result;6 Console.WriteLine($"{result} > {DateTime.Now}");7 }8 }
The above Code request will surely report an error for a period of time [you want to test the url address as an internal local area network ];
Some people may say that this is a single-thread estimate. I would like to say that if you use using in multiple threads, it may be okay, however, it is a huge overhead for the CPU to enable the thread. The frequency of all requests that really overwhelm the api is not very high;
Ii. Optimization scenarios
1 HttpClient client = new HttpClient (); // here the client can be initialized in singleton Mode 2 while (true) 3 {4 var result = client. getStringAsync ("http://www.xxxx.com /"). result; 5 Console. writeLine ($ "{result}> {DateTime. now} "); 6}
The Asynchronous Method is thread-safe, so you don't have to worry about multithreading!
2017.1.5
Note that DeleteAsync may cause problems in high concurrency.
Iii. DNS BUG
I don't think this problem can be solved. If Nginx is used, I think this problem can be solved temporarily;
Defects in HttpClient on InfoQ: http://www.infoq.com/cn/news/2016/09/HttpClient
Digress: Best Singleton Mode
private static HttpClient client; public static HttpClient Singleton { get { if (client == null) { Interlocked.CompareExchange(ref client,new HttpClient(),null); } return client; } }