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

Please refer to my previous question for the Sockets code example : sometimes (rarely) packets are lost upon receipt

I need to always get data from a UDP multicast socket. This is a one-way compromise. I just need to listen to the new data and process it as soon as possible.

Should I use while(true) ? I don't like while(true) because, in my opinion, this creates a lot of extra work for the processor. Perhaps C # offers other callback methods or something else?

+6
source share
3 answers

2 to 6 sockets (comments) are probably located in an interesting place where either blocking or async IO will work fine, since you are not soaking the machine with threads. With 2000 packets per second, it sounds like there is a lot to keep the stream busy. You don’t have to worry about while(true) in terms of performance, as the Receive method will block until data is available, so it never does anything in a hot loop. However! Personally, from a cosmetic point of view, I agree that while(true) is an unnecessary blot, so if you use a blocking approach, you might think:

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

which will automatically close when the socket is closed.

You can also do this using the BeginReceive and Socket.ReceiveAsync , which do not use a blocking call, but instead use either an event or a callback. They are especially useful when handling a large number of connections.

Personally, I try to use Socket.Available ; if it is positive, that is, the data is buffered and ready to eat, so the simple Receive can be used to quickly retrieve this data without the context switch. If it is zero, then there is currently no data, so an asynchronous call may be more appropriate. This balances the context switches with direct calls. Note that the ReceiveAsync method also has a built-in built-in function that returns a value from ReceiveAsync (which is true if the operation is incomplete and the callback will be called later - and false if the operation is already and the no callback will be called).

+3
source

The best way to program sockets is to use their Async counterparts. Instead of starting endless loops, you should call BeginReceive and set its callback method, which will fire when the transfer is complete. Thus, you will retain control over your application and use much less resources.

Link: http://msdn.microsoft.com/en-us/library/bbx2eya8.aspx#Y0

+1
source

The Async method is best suited.

However, in this case, if you use while (true), which contains socket.Receive (buf), there is no extra work for the processor, because if you do not set a timeout, block the loop until the data arrives.

0
source

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


All Articles