pm100 pm100 - 7 months ago 38
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)

foo();
bar();
// compute stuff
var x = GetThingFromOtherServerViaHttp();
// compute more stuff
wiz(x);


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

client.PostAsync.Wait()


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

client.PostAsync.Result()


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

From http://blogs.msdn.com/b/pfxteam/archive/2012/04/13/10293638.aspx:

return Task.Run(() => Client.PostAsync()).Result;