Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantage of Synchronous vs asynchronous in TCP socket connection

I'm currently learning C# coming from a java background. To get my feet wet I decided to make a simple SMTP mail application. And I learned very quickly that C# offers support for both Synchronous and Asynchronous sockets.

From what I can see, there is no real advantage to using a synchronous socket vs an asynchronous since the latter doesn't block and therefor doesn't require you to create a new thread each time. There also doesn't seem to be a noticeable overhead to using one or the other.

So my question is this, is there an advantage to using a synchronous socket or is it better to just stick with asynchronous in most cases?

like image 796
Mo H. Avatar asked Nov 11 '14 11:11

Mo H.


People also ask

What is the difference between synchronous sockets and asynchronous sockets?

The send, receive, and reply operations may be synchronous or asynchronous. A synchronous operation blocks a process till the operation completes. An asynchronous operation is non-blocking and only initiates the operation.

What is asynchronous socket connection?

In an asynchronous socket, you CAN do other stuff while waiting for the client to send data to you, so now you CAN have multiple clients connecting to you. Synchronous uses a function like receive() which blocks until it gets a message. Asynchronous has beginReceive() endReceive() or similar functions.

What is asynchronous TCP?

A synchronous API does things while you call it: for example, send() moves data to the TCP send buffer and returns when it is done. An asynchronous API starts when you call it, executes independently after it returns to you, and calls you back or provides an interrogable handle via which completion is notified.

What are synchronous and asynchronous modes of operation in parallelism?

In synchronous operations tasks are performed one at a time and only when one is completed, the following is unblocked. In other words, you need to wait for a task to finish to move to the next one. In asynchronous operations, on the other hand, you can move to another task before the previous one finishes.


1 Answers

Async IO saves threads. A thread consumes (usually) 1MB of stack memory. This is the main reason to use async IO when the number of concurrent outstanding IO operations becomes big. According to my measurements OS scalability is not a concern until you get into the thousands of threads.

The main disadvantage is that it requires more development effort to make the same application work at the same level of reliability.

I have written about this tradeoff at length. Also: Should we switch to use async I/O by default?

It is objectively wrong advice to recommend to always use async IO.

like image 188
usr Avatar answered Sep 27 '22 02:09

usr