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) {
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).
source share