I tried to compare the performance between synchronous and asynchronous methods when reading small amounts of data that had already been received.
So I send the data and make sure it is waiting on the receiving socket(same program).
source.Send(sendBuffer);
while (target.Available != sendBuffer.Length)
Thread.Sleep(50);
SocketAsyncEventArgs arg = new SocketAsyncEventArgs();
arg.Completed += AsyncCallback;
arg.SetBuffer(receiveBuffer, 0, sendBuffer.Length);
if(target.ReceiveAsync (arg))
{
//Pending request
//999 out of 1000 times we end up here
}
To my surprise the the ReceiveAsync call almost never finished synchronously.
I would assume that a ReceiveAsync would return synchronously and perform as fast as Receive but since it almost never happen I can’t tell.
Were my expectations of ReceiveAsync wrong here?
Would it be better to always first check target.Available and do a Receive if there is enough bytes available?
This kind of breaks some of the benefits with using ReceiveAsync rather than BeginReceive, that is why I’m writing this question.
ReceiveAsyncjust calls into the underlying Winsock subsystem.ReceiveAsyncuses what is called Overlapped IO (asynchronous IO). In the case of a socket created to use overlapped IO: “Regardless of whether or not the incoming data fills all the buffers, the completion indication occurs for overlapped sockets”. Where “completion indication” is the callback that will be called asynchronously. Which meansReceiveAsyncwill be asynchronous all the time (unless there’s an error).