Skip to content

How to use .NET HttpClient synchronously (if you must)

As of .NET Framework 4.5, HttpClient has been the preferred way of consuming RESTful APIs since it builds upon the simplicity of WebClient with the ability to use a single object to make multiple requests (even though it implements IDisposable, newing one up in a using statement every time you make a request will exhaust the available sockets). It’s a more modern and flexible implementation since it takes an asynchronous-first approach, but you may need to use it synchronously if you have to support older versions of .NET. Here’s how to use HttpClient synchronously:

var result = _httpClient.GetAsync(beerUrl).Result;

if (result.IsSuccessStatusCode)
	string content = result.Content.ReadAsStringAsync().Result;
	header = JsonConvert.DeserializeObject<Beer>(content);

The key here is the use of .Result after the async methods. This makes them synchronous, and you can use this code in your non-async methods.

Published inTips & Tricks

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *