Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

should I use while(true) to receive data from Socket?

Tags:

c#

sockets

Please refer my previous question for code sample Sockets: sometimes (rarely) packets are lost during receiving

I need to receive data always from UDP multicast socket. This is one-way comminication I just need to listen for new data and process it asap.

Should I use while(true)? I don't like while(true) because in my opinion this produce a lot of extra-work for processor. Probably c# offers other call-back techniques or something?

like image 247
Oleg Vazhnev Avatar asked Mar 23 '12 06:03

Oleg Vazhnev


1 Answers

2 to 6 sockets (comments) is probably in the interesting place where either blocking or async IO will work fine, since you aren't swamping the machine with threads. With 2000 packets per second, it sounds like there is plenty to keep the threads busy. You don't need to worry about while(true) from a performance perspective, since the Receive method will block until data is available, so it is never doing a hot-loop of doing nothing. However! Personally, from a cosmetic perspective, I agree while(true) is an unnecessary blot, so if you are using the blocking approach, maybe consider:

int bytesRead;
while((bytesRead = socket.Receive(buffer)) > 0) {
    // process bytesRead from buffer
}

which will exit cleanly when the socket is closed.

You can also do this with either the BeginReceive and Socket.ReceiveAsync methods, which doesn't use a blocking call, but instead uses either an event or callback. These are particularly useful when handling lots of connections.

Personally, what I tend to do is use Socket.Available; if this is positive, then there is data buffered and ready to consume, so a simple Receive can be used to fetch that data promptly and without a context-switch. If it is zero, then no data is currently available, so an async call may be more appropriate. This balances context-switches with direct calls. Note that the ReceiveAsync approach has this built in too, via the return value from ReceiveAsync (which is true if the operation is incomplete, and a callback will be invoked later - and false if the operation is already complete, and no callback will be invoked).

like image 120
Marc Gravell Avatar answered Sep 27 '22 23:09

Marc Gravell