pm100 pm100 - 1 year ago 59
C# Question

best way to use the nice .net 4.5 HttpClient synchronously

I like the new System.Net.Http.HttpClient class. It has a nice simple API, it doesn't throw on normal errors. But its async only.

I need code that goes (deep inside a server)

// compute stuff
var x = GetThingFromOtherServerViaHttp();
// compute more stuff

classic sequential synchronous code. I saw several SO question that were similar but never actually ended up saying 'do this'. I looked at


the world screams 'dont do this'. How about:


isnt this just Wait in disguise?

In the end I ended up passing in a lambda callback that processed the result and then awoke the calling thread that was explicitly waiting on a EventWaitHandle. A lot of plumbing. Is there something a little simpler or shoul I just go back to using the old http clients

EDIT:After further reading I suspect that this code has the same issues as Wait and Result, its just a more longwinded deadlock

Answer Source


return Task.Run(() => Client.PostAsync()).Result;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download