优化前的代码
using System;
using System.Net.Http;
namespace ConsoleApplication
{
public class Program
{
public static async Task Main(string[] args)
{
Console.WriteLine("Starting connections");
for(int i = 0; i<10; i++)
{
using(var client = new HttpClient())
{
var result = await client.GetAsync("http://aspnetmonsters.com");
Console.WriteLine(result.StatusCode);
}
}
Console.WriteLine("Connections done");
}
}
}
优化后
using System;
using System.Net.Http;
namespace ConsoleApplication
{
public class Program
{
private static HttpClient Client = new HttpClient();
public static async Task Main(string[] args)
{
Console.WriteLine("Starting connections");
for(int i = 0; i<10; i++)
{
var result = await Client.GetAsync("http://aspnetmonsters.com");
Console.WriteLine(result.StatusCode);
}
Console.WriteLine("Connections done");
Console.ReadLine();
}
}
}
你需要记住这两件事:
- 让你的
HttpClient
静态。 - 除非您明确地寻找特定行为(例如导致您的服务失败),否则不要丢弃或包装您的使用。
HttpClient
参考:https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.8