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?
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 theReceivemethod will block until data is available, so it is never doing a hot-loop of doing nothing. However! Personally, from a cosmetic perspective, I agreewhile(true)is an unnecessary blot, so if you are using the blocking approach, maybe consider:which will exit cleanly when the socket is closed.
You can also do this with either the
BeginReceiveandSocket.ReceiveAsyncmethods, 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 simpleReceivecan 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 theReceiveAsyncapproach has this built in too, via the return value fromReceiveAsync(which istrueif the operation is incomplete, and a callback will be invoked later – andfalseif the operation is already complete, and no callback will be invoked).