Question

I have been a staunch advocate of never blocking on async code. I felt it was always better to use a synchronous API than to run the less efficient state machine generated by the compiler even if there is no chance of deadlock.

But in the specific case of System.Net.HttpClient with code that cannot go async all the way down (like a console app), isn't it better to take advantage of the connection caching of HttpClient than to use something like WebRequest that must negotiate the TCP session on each invocation?

I'm starting to think the benefits of re-using HttpClient, even if you block with .Result, outweigh the reasons for using a synchronous API instead.

This is assuming of course that the HttpClient is a shared instance, would be re-used and is operating in a context-free environment like a console app or asp.net core.

Was it helpful?

Solution

You don't need to block in a console app anymore.

https://stackoverflow.com/questions/9208921/cant-specify-the-async-modifier-on-the-main-method-of-a-console-app

Even when you did, you could just call a MainAsync() from Main and block on that. There's no need to block on a HttpClient call and you shouldn't.

I felt it was always better to use a synchronous API than to run the less efficient state machine generated by the compiler

Your feeling is wrong. Even if the framework you are working in doesn't reuse the thread while you are awaiting, you can still make use of the thread while you await.

OTHER TIPS

Personally, I find it easier to understand and reason about threaded code than async code (not directly contradicting your inclination, but suggesting I may have a different bias).

I'm not sure what you mean about HttpClient not going 'async all the way down'. I haven't looked at the .net implementation of HttpClient, but there is no reason it cannot be implemented async all the way down - just using epoll/wantformultipleevents/select.

As near as I can tell, HttpClient is the newer MSFT .net API. Usually when MSFT comes up with new APIs for something they already support, they eventually deprecate/desupport the older API, so I would prefer HttpClient for that reason.

Whether or not connection caching helps you - depends on the nature of your application. It can help or hurt. If you make requests (using the same http client) to the same server, connection keepalives will help. If you do NOT do this, they will strictly HURT your performance.

Licensed under: CC-BY-SA with attribution
scroll top