HttpClient 异步安全吗?
Is HttpClient async safe?
突然有点疑惑了。根据 MSDN,HttpClient 是线程安全的(至少对于 GetAsync 或 PostAsync)。
但如果我这样做
List<Task> tasks= new List<Task>();
tasks.Add(_httpClient.PostAsync(url1, requestMessage1));
tasks.Add(_httpClient.PostAsync(url2, requestMessage2));
Tasks.Wait(tasks);
我会一直得到正确的结果吗,因为现在两个调用都来自同一个线程?
Will I get correct results back all the time as both calls come from the same thread now?
是的。这就是 HttpClient 的缩进用法。
"An HttpClient instance is a collection of settings applied to all requests executed by that instance. In addition, every HttpClient instance uses its own connection pool"
突然有点疑惑了。根据 MSDN,HttpClient 是线程安全的(至少对于 GetAsync 或 PostAsync)。
但如果我这样做
List<Task> tasks= new List<Task>();
tasks.Add(_httpClient.PostAsync(url1, requestMessage1));
tasks.Add(_httpClient.PostAsync(url2, requestMessage2));
Tasks.Wait(tasks);
我会一直得到正确的结果吗,因为现在两个调用都来自同一个线程?
Will I get correct results back all the time as both calls come from the same thread now?
是的。这就是 HttpClient 的缩进用法。
"An HttpClient instance is a collection of settings applied to all requests executed by that instance. In addition, every HttpClient instance uses its own connection pool"