rspec/rules/S4470/rule.adoc

54 lines
1.6 KiB
Plaintext
Raw Normal View History

2020-12-23 14:59:06 +01:00
It is well documented that while ``HttpClient`` implements ``IDisposable``, it is intended to be reused, which means not wrapping it in a ``using`` statement.
As noted in the documentation:
{quote}
HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors.
{quote}
2020-12-23 14:59:06 +01:00
This rule raises an issue when an instance of a ``HttpClient`` is created within a ``using`` statement.
== Noncompliant Code Example
----
namespace MyLibrary
{
public class Foo
{
public async Task Bar()
{
using (var client = new HttpClient()) // Noncompliant
{
await client.GetAsync("https://www.sonarqube.org/");
}
}
}
}
----
== Compliant Solution
----
namespace MyLibrary
{
public class Foo
{
private static HttpClient client = new HttpClient();
public async Task Bar()
{
await client.GetAsync("https://www.sonarqube.org/");
}
}
}
----
== See
* https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.110).aspx?f=255&mspperror=-2147217396#Anchor_5[HttpClient Class]
* https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client[Call a Web API From a .NET Client (C#)]
* https://github.com/mspnp/performance-optimization/blob/master/ImproperInstantiation/docs/LoadTesting.md[Microsoft Patterns & Practices]