HttpClient 并发使用是否安全? [英] Is HttpClient safe to use concurrently?

查看:40
本文介绍了HttpClient 并发使用是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我能找到的关于 HttpClient 用法的所有示例中,它用于一次性调用.但是,如果我有一个持久的客户端情况,可以同时发出多个请求呢?基本上,针对 HttpClient 的同一实例同时在 2 个线程上调用 client.PostAsync 是否安全.

In all the examples I can find of usages of HttpClient, it is used for one off calls. But what if I have a persistent client situation, where several requests can be made concurrently? Basically, is it safe to call client.PostAsync on 2 threads at once against the same instance of HttpClient.

我并不是真的在这里寻找实验结果.作为一个工作示例可能只是一个侥幸(和一个持久的),一个失败的例子可能是一个错误的配置问题.理想情况下,我正在寻找有关 HttpClient 中并发处理问题的权威答案.

I am not really looking for experimental results here. As a working example could simply be a fluke (and a persistent one at that), and a failing example can be a misconfiguration issue. Ideally I'm looking for some authoritative answer to the question of concurrency handling in HttpClient.

推荐答案

根据 Microsoft Docs,从 .NET 4.5 开始,以下实例方法是线程安全的(感谢 @ischell):

According to Microsoft Docs, since .NET 4.5 The following instance methods are thread safe (thanks @ischell):

CancelPendingRequests
DeleteAsync
GetAsync
GetByteArrayAsync
GetStreamAsync
GetStringAsync
PostAsync
PutAsync
SendAsync
PatchAsync

这篇关于HttpClient 并发使用是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆