Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Sockets Async vs Mulithreading

I am working on a project where I am to extract information continually from multiple servers (fewer than 1000) and write most of the information into a database. I've narrowed down my choices to 2:

Edit: This is a client, so I will be generating the connections and requesting information periodically.

1 - Using the asynchronous approach, create N sockets to poll, decide whether the information will be written into the database on the callback and put the useful information into a buffer. Then write the information from the buffer using a timer.

2 - Using the multithreading approach, create N threads with one socket per thread. The buffer of the useful information would remain on the main thread and so would the cyclic writing.

Both options use in fact multiple threads, only the second one seems to add an extra difficulty of creating each of the threads manually. Are there any merits to it? Is the writing by using a timer wise?

like image 361
Alex Avatar asked Feb 11 '23 06:02

Alex


1 Answers

With 1000 connections async IO is usually a good idea because it does not block threads while the IO is in progress. (It does not even use a background thread to wait.) That makes (1) the better alternative.

It is not clear from the question what you would need a timer for. Maybe for buffering writes? That would be valid but it seems to have nothing to do with the question.

Polling has no place in a modern async IO application. The system calls your callback (or completes your IO Task) when it is done. The callback is queued to the thread-pool. This allows you to not worry about that. It just happens.

The code that reads data should look like this:

while (true) {
 var msg = await ReadMessageAsync(socket);
 if (msg == null) break;
 await WriteDataAsync(msg);
}

Very simple. No blocking of threads. No callbacks.

like image 168
usr Avatar answered Feb 13 '23 21:02

usr