rspec/rules/S4470/rule.adoc

59 lines
1.6 KiB
Plaintext
Raw Normal View History

2021-01-27 13:42:22 +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.
2021-02-02 15:02:10 +01:00
As noted in the documentation:
2021-02-02 15:02:10 +01:00
2021-01-06 17:38:34 +01:00
____
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.
____
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
This rule raises an issue when an instance of a ``++HttpClient++`` is created within a ``++using++`` statement.
== Noncompliant Code Example
2022-02-04 17:28:24 +01:00
[source,text]
----
namespace MyLibrary
{
public class Foo
{
public async Task Bar()
{
using (var client = new HttpClient()) // Noncompliant
{
await client.GetAsync("https://www.sonarqube.org/");
}
}
}
}
----
== Compliant Solution
2022-02-04 17:28:24 +01:00
[source,text]
----
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]