Using HttpClient

Jassim Al Rahma 1,616 Reputation points
2023-01-14T11:53:34.77+00:00

Hi,

I want to ask. is enough to have:

private static readonly HttpClient Client;

in order to have the best performance? or there is more to do?

Thanks,

Jassin

Developer technologies C#
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Castorix31 90,521 Reputation points
    2023-01-14T12:27:21.8366667+00:00

    Yes, see MSDN samples : HttpClient

    Although I still use HttpWebRequest in some cases when HttpClient freezes, even if MS says

    "We don't recommend that you use HttpWebRequest for new development. Instead, use the System.Net.Http.HttpClient class."

    0 comments No comments

  2. P a u l 10,761 Reputation points
    2023-01-14T12:32:41.9833333+00:00

    Performance wise, and also for simple console apps (particularly if they aren't long-running), creating a single HttpClient is perfectly fine.

    If you have a long-running app then you're still fine with regard to performance, although the underlying HttpMessageHandler (the component of HttpClient that manages the connection) won't be aware of any DNS changes that occur during the lifetime of the object.

    It's preferred that rather than creating HttpClient instances yourself, you use a factory instead, which will substitute out the HttpMessageHandler whenever an instance of HttpClient is produced via it. This would typically be configured when registering your services with the AddHttpClient method.

    This article goes through this in detail:

    [https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests#issues-with-the-original-httpclient-class-available-in-net


  3. Ernest 1 Reputation point
    2023-01-31T09:31:09.0866667+00:00

    There are some caveats to be aware of as it depends on what you later do with that client. Be aware of sockets exhaustion (although you are using a static field, so this shouldn't be a problem) and changing DNS'. In general, it is recommended to use the same base URL for a single HttpClient instance throughout the lifetime of the application. Using an IHttpClientFactory helps to avoid common pitfalls with HTTP clients.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.