Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the Asynchronous mode is better than the Synchronous one when handling clients requests?

I have a client-server project and was searching for the better way to handle the requests from the clients. Some people advised that the Asynchronous mode is better than the synchronous one and the thread pool mode.
My question is why? And are there disadvantages in the Asynchronous mode ?

like image 392
Mohamad Alhamoud Avatar asked Dec 12 '22 21:12

Mohamad Alhamoud


2 Answers

Yes, asynchronous requests can often be handled without the expense of a thread. The operating system has special support for them, features like overlapped I/O and completion ports. What they essentially do is leverage the expense of a kernel thread, one that's needed anyway because a driver needs to be able to handle multiple requests from multiple user mode programs. The .NET framework readily takes advantage of that in its BeginXxx() methods.

Using threadpool threads is cheap too, but you are subject to the behavior of the threadpool scheduler. Which doesn't much like starting more TP threads then there are cores. TP threads should never be used for code that can stay blocked for a while, pretty typical for CS tasks like making a connection.

Error handling is very difficult in asynchronous code. You typically have very little context when the EndXxxx() method raises an exception. It happens on a callback thread, very far away from the main logic. Okay when you can shrug "didn't happen, lets log it", total bedlam and redrum when the program's state depends on it. Always choose synchronous mode in the latter case.

like image 59
Hans Passant Avatar answered Apr 27 '23 18:04

Hans Passant


You don't want to block the UI. With asynchronous operation you can do other things while waiting for the server to respond.

like image 34
chum of chance Avatar answered Apr 27 '23 19:04

chum of chance