Coder Perfect

Why should you use HttpClient for synchronized connections?

Problem

I’m creating a class library that will allow me to connect with an API. I need to make an API request and then process the XML return. Although I can appreciate the advantages of utilizing HttpClient for asynchronous communication, the work I’m doing is entirely synchronous, therefore I don’t see any substantial advantages above HttpWebRequest.

I’d be grateful if anyone could give some light on this. I’m not a fan of experimenting with new technologies just for the purpose of it.

Asked by Ketchup

Solution #1

For synchronous requests, HttpClient is perfectly adequate:

using (var client = new HttpClient())
{
    var response = client.GetAsync("http://google.com").Result;

    if (response.IsSuccessStatusCode)
    {
        var responseContent = response.Content; 

        // by calling .Result you are synchronously reading the result
        string responseString = responseContent.ReadAsStringAsync().Result;

        Console.WriteLine(responseString);
    }
}

Why should you use HttpClient instead of WebRequest? Well, HttpClient is the new kid on the block, and it might have some advantages over the old client.

Answered by Darin Dimitrov

Solution #2

I’d want to reiterate Donny V.’s and Josh’s responses.

(And, if I had the reputation, I’d upvote.)

I can’t recall the last time, if ever, I was thankful for HttpWebRequest’s ability to throw exceptions for status codes greater than 400. To avoid these problems, you must catch exceptions quickly and map them to non-exception response mechanisms in your code…which is difficult, time-consuming, and error-prone in and of itself. It’s almost always preferable for the Http driver to just inform your application code what was returned, and leave it up to you to decide how to behave, whether you’re talking with a database or constructing a custom web proxy.

As a result, HttpClient is the better choice.

Answered by trev

Solution #3

For anyone who is reading this today, HttpClient now provides a synchronous Send method in.NET 5.0. https://github.com/dotnet/runtime/pull/34948

The reasons for this were extensively explained here: https://github.com/dotnet/runtime/issues/32125

As a result, you can use this instead of SendAsync. As an example,

public string GetValue()
{
    var client = new HttpClient();

    var webRequest = new HttpRequestMessage(HttpMethod.Post, "http://your-api.com")
    {
        Content = new StringContent("{ 'some': 'value' }", Encoding.UTF8, "application/json")
    };

    var response = client.Send(webRequest);

    using var reader = new StreamReader(response.Content.ReadAsStream());

    return reader.ReadToEnd();
}

This is simply a simple sample; it’s not ready for production.

Answered by alexs

Solution #4

public static class AsyncHelper  
{
    private static readonly TaskFactory _taskFactory = new
        TaskFactory(CancellationToken.None,
                    TaskCreationOptions.None,
                    TaskContinuationOptions.None,
                    TaskScheduler.Default);

    public static TResult RunSync<TResult>(Func<Task<TResult>> func)
        => _taskFactory
            .StartNew(func)
            .Unwrap()
            .GetAwaiter()
            .GetResult();

    public static void RunSync(Func<Task> func)
        => _taskFactory
            .StartNew(func)
            .Unwrap()
            .GetAwaiter()
            .GetResult();
}

Then

AsyncHelper.RunSync(() => DoAsyncStuff());

You can safely call async methods from sync methods if you use that class and pass your async method as a parameter.

Here’s how it works: https://cpratt.co/async-tips-tricks/

Answered by Lean Bonaventura

Solution #5

If you’re creating a class library, it’s possible that your library’s users will want to utilize it asynchronously. That, I believe, is the most important reason.

You also have no idea how your library will be used. Users may be processing a large number of requests, and processing them asynchronously will help it run faster and more efficiently.

If you can accomplish it easily, don’t put the burden on your library’s users by attempting to make the flow asynchronous when you can do it for them.

The only time I wouldn’t use the async version is if I needed to support an older version of.NET that didn’t have async support built in.

Answered by Josh Smeaton

Post is based on https://stackoverflow.com/questions/14435520/why-use-httpclient-for-synchronous-connection