Ehsan Abidi
Ehsan Abidi

Reputation: 959

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?

Upvotes: 1

Views: 3757

Answers (3)

ronenfe
ronenfe

Reputation: 2405

All HttpClient methods are async and will deadlock when used in ASP.NET web forms.

Microsoft for some reason didn't create them synchronous.

Upvotes: 0

Ali Bahrami
Ali Bahrami

Reputation: 6073

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();
    }
}

Upvotes: 2

Patrick Hofman
Patrick Hofman

Reputation: 156978

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:

  • CancelPendingRequests
  • DeleteAsync
  • GetAsync
  • GetByteArrayAsync
  • GetStreamAsync
  • GetStringAsync
  • PostAsync
  • PutAsync
  • SendAsync

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.

Upvotes: 0

Related Questions