'using .NET 4.5 HttpClient in ASP.NET Web form
I Want to use .NET 4.5 HttpClient class in ASP.NET Web Form. I read in the C# 5.0 in a NutShell Book (page 663):
Unlike with WebClient, to get the best performance with HttpClient, you must reuse same instance (otherwise things such as DNS resolution may be unnecessarily repeated.) HttpClient permits concurrent operations, . . .
In our ASP.NET web Form website ,we need to connect to another website. I have created an instance of HttpClient in the Application property to use a single instance in all requests. in Global.asax something like this is written:
Application.Add("MateCatWorker", new HttpClient());
My question is that:Is it a good practice?
Solution 1:[1]
According to the HttpClient Class on MSDN these methods are thread-safe:
- CancelPendingRequests
- DeleteAsyn
- GetAsync
- GetByteArrayAsync
- GetStreamAsync
- GetStringAsync
- PostAsync
- PutAsync
- SendAsync
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. Below is an example using HttpClient correctly.
And I recommend not to store the HttpClient into Application, I'm not a fan of singleton but create a singleton class for that is much more better.
public class GoodHttpClient
{
// OK
private static readonly _httpClient HttpClient;
static GoodHttpClient()
{
_httpClient = new HttpClient();
}
}
Solution 2:[2]
A good practice: no, not in my opinion. Note that the application context might be synced between instances in a web farm, so I wouldn't really use that to store such variable.
Does it work? Yes, if you use one of the async methods mentioned in the remarks section of this MSDN article, since those are safe to use in multiple threads:
CancelPendingRequestsDeleteAsyncGetAsyncGetByteArrayAsyncGetStreamAsyncGetStringAsyncPostAsyncPutAsyncSendAsync
Honestly, I would not worry too much about it. If you run calls in a tight loop, reuse the same object. If not, don't reuse it.
Solution 3:[3]
All HttpClient methods are async and will deadlock when used in ASP.NET web forms.
Microsoft for some reason didn't create them synchronous.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Patrick Hofman |
| Solution 3 | Ronen Festinger |
