Per MSDN Documentation on Socket.ReceiveAsync
:
Returns true if the I/O operation is pending. The
SocketAsyncEventArgs.Completed
event on the e parameter will be raised
upon completion of the operation.
Returns false if the I/O operation
completed synchronously. In this case, The
SocketAsyncEventArgs.Completed
event on the e parameter will not be
raised and the e object passed as a parameter may be examined
immediately after the method call returns to retrieve the result of
the operation.
To answer your question, no it will not create an infinite loop/recursion.
Your ListenForData
method will only call OnDataReception
once per call to ReceiveAsync
. Since you are calling ListenForData
in OnDataReception
and not in a loop, it will look like this:
ListenForData called!
(time elapses)
OnDataReception called!
ListenForData called!
(time elapses)
OnDataReception called!
ListenForData called!
...
This is almost identical to using Socket.BeginReceive
, passing an AsyncCallback
and then calling Socket.EndReceive
followed by another Socket.BeginReceive
in the callback. It's an indefinite loop but not an infinite one.
See:
void StartReceiving()
{
// Start receiving asynchronously...
socket.BeginReceive(recvBuffer, 0, recvBuffer.Length, SocketFlags.None, OnDataReceived, null);
}
void OnDataReceived(IAsyncResult result)
{
// Finish receiving this data.
var numberOfBytesReceived = socket.EndReceive(result);
// Start receiving asynchronously again...
if(numberOfBytesReceived > 0 && socket.Connected)
socket.BeginReceive(recvBuffer, 0, recvBuffer.Length, SocketFlags.None, OnDataReceived, null);
}