C # Sockets Async vs Mulithreading

I am working on a project where I have to constantly extract information from several servers (less than 1000) and write most of the information to the database. I narrowed my choices to 2:

Edit: this is a client, so I will periodically create connections and request information.

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

2 - Using multithreading, create N threads with one socket per thread. A buffer of useful information will remain on the main thread, as well as loop recording.

Both options actually use several threads, only the second seems to create additional difficulty for creating each of the threads manually. Is there any merit? Is recording using a timer?

+4
source share
4 answers

When using 1000 async connections, IO is usually a good idea, as it does not block threads while IO is running. (It does not even use the background thread to wait.) This makes (1) a better alternative.

It is not clear why you need a timer. Maybe for buffering writes? That would be fair, but it seems to have nothing to do with the issue.

-. ( IO Task), . . . .

, , :

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

. . .

+6

" ", , , . - .NET. , .

, , , . , , - , MSMQ . , , async (.. " " ), (), .

+1

- , , . , , . , , .

BlockingCollection <T> . , . , :

BlockingCollection<DataType> _theQueue = new BlockingCollection<DataType>(MaxBufferSize);

// add data with
_theQueue.Add(Dataitem);

// service the queue with a simple loop
foreach (var dataItem in _theQueue.GetConsumingEnumerable())
{
    // write dataItem to the database
}

(.. ), . , , , .

// mark the queue as complete for adding
_theQueue.CompleteAdding();

, .

, , (10? 100? 1000?) . , , , . - , , .

+1

(1) , . , .

A constant queue will also give you some stability.

0
source

Source: https://habr.com/ru/post/1569436/


All Articles