C# – Better to Block on Async with HttpClient or Use Synchronous API?

asyncchttp-request

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.

Best Answer

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.

Related Topic