What's the right way to use HttpClient synchronously?
For anyone coming across this now, .NET 5.0 has added a synchronous Send
method to HttpClient
. https://github.com/dotnet/runtime/pull/34948
You can therefore use this instead of SendAsync
. For 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 code is just a simplified example, it's not production ready.
Why use HttpClient for Synchronous Connection
For anyone coming across this now, .NET 5.0 has added a synchronous Send
method to HttpClient
. https://github.com/dotnet/runtime/pull/34948
The merits as to why where discussed at length here: https://github.com/dotnet/runtime/issues/32125
You can therefore use this instead of SendAsync
. For 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 code is just a simplified example - it's not production ready.
Why use HttpClient over HttpWebRequest for synchronous requests
HttpClient
is designed to give more control over http protocol, where else doing same in HttpWebRequest
or WebClient
was not that straight forward. Apart from asynchronous, there are many benefits of HttpClient
Benefits of HttpClient
Biggest benefit of HttpClient
is plugin architecture, that lets you change underlying behavior of HTTP protocol easily.
HttpClient
is extensible, underlyingHttpMessageHandler
allows you to completely by pass underlying Microsoft's HttpClient implementation and you can plugin your own implementation. For example, in iOS and Android, instead of using .Net's HttpClient, we could use native Http stack.- It is easy to replace caching, cookies by customizing
HttpMessageHandler
CancellationToken
support is excellent when we want to cancel a long running Http request.- Not shiny, but important, Multi threaded,
HttpClient
is optimized to manage multiple requests with single instance. CPU time is utilized very efficiently without using too many locks (synchronous operations depend on locks, which is considerable overhead on CPU). Today we are living in world of micro services. In server with many clients to serve and mobile OS, CPU time is costly.
Drawbacks
Only drawback is async/await
, you can't simply use async libraries easily in synchronous code without using a Task Runner or deadlocks. Though there are many libraries supporting how to synchronously use async code.
There is no great benefit of HttpClient
on Desktop application with lots of CPU time as spare.
best way to use the nice .net 4.5 HttpClient synchronously
From http://blogs.msdn.com/b/pfxteam/archive/2012/04/13/10293638.aspx:
return Task.Run(() => Client.PostAsync()).Result;
Related Topics
Wait for a While Without Blocking Main Thread
Compile-Time and Runtime Casting C#
C# Regular Expressions, String Between Single Quotes
Hook on Default "Paste" Event of Winforms Textbox Control
Pass a Value from One Form to Another
.Net:How to Get the Type of a Null Object
Is This Thread.Abort() Normal and Safe
How to Quickly Up-Cast Object[,] into Double[,]
C# Arrow Key Input for a Console App
Strange Behaviour of Console.Readkey() with Multithreading
Converting ASP.NET MVC Razor @Helper Function into a Method of a Helper Class
Trying to Debug Windows Store App from Dump Files
String Interpolation with Format Variable
Incorrectly Aligned or Overlapped by a Non-Object Field Error
Bring Another Processes Window to Foreground When It Has Showintaskbar = False