gpt4 book ai didi

c# - RestClient 应该是单例还是为每个请求创建新实例

转载 作者:行者123 更新时间:2023-12-01 19:25:45 25 4
gpt4 key购买 nike

ASP.Net HttpClient 是一次性的,很多文章都说由于性能原因应该使用单例模式来使用它。但是当我看到 RestClient 时,它无法被处置,并且在 Recommended-Usage 中页面示例每次都会new RestClient。我应该为 RestClient 使用单例模式还是应该每次都new?如果我每次new都会有性能问题吗?

RestSharp GitHub

一些引用:

Do HttpClient and HttpClientHandler have to be disposed

YOU'RE USING HTTPCLIENT WRONG AND IT IS DESTABILIZING YOUR SOFTWARE

最佳答案

对于 Restclient 版本 <107:

should I use singleton pattern for RestClient or should I new iteverytime, if I new it everytime will any performance concern?

推荐使用方式RestSharp是为每个请求创建一个新实例。

它与 HttpClient 推荐的单例方法不同。原因是under the hood RestSharp使用HttpWebRequest用于 HTTP 交互,而不是 HttpClient 。这就是使用模型不同的原因。

If I create it everytime do I get performance issue just like theHttpClient?

不应创建 HttpClient 的新实例的主要原因对于每个请求都不是性能考虑因素。创建和初始化所花费的时间只占后续网络调用所花费时间的一小部分。使用HttpClient单例实例的主要原因is the following :

HttpClient is intended to be instantiated once and re-used throughoutthe life of an application. Instantiating an HttpClient class forevery request will exhaust the number of sockets available under heavyloads. This will result in SocketException errors.

RestSharp不使用连接池作为 HttpClient并且使用后不会留下打开的 socket 。这就是为什么创建 RestClient 的新实例是安全的(并且推荐)。根据请求。

如果您使用 RestClient 的重用实例,您会获得性能提升吗? ?那么,您将节省创建对象及其初始化的时间。然而这个时间非常接近 0而且,这只是后续网络调用所花费的时间的一小部分。您不会重用其他 .NET 对象,例如 List<T>出于性能考虑,是吗?您应该对 RestClient 执行相同的操作。它只是以暗示这种使用场景的方式开发的。

关于c# - RestClient 应该是单例还是为每个请求创建新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49588205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com