I am writing a high performance socket application in .NET. I have the following code to read from the socket asynchronously.
Private Sub Read(ByVal ar As IAsyncResult)
Dim asyncState = DirectCast(ar.AsyncState, ReadAsyncState)
Dim buffer = asyncState.Buffer
Dim client = asyncState.client
Try
Dim stream = client.GetStream()
'Complete the asynchronous read and get the first block of data.
If stream IsNot Nothing AndAlso stream.CanRead Then
Dim byteCount = stream.EndRead(ar)
If byteCount = 0 Then
'If there is no data when an asynchronous read completes it is because the client closed the connection.
Me.RemoveClient(client)
Else
'Notify any listeners that a message was received.
RaiseEvent MessageReceived(client, buffer.Take(byteCount).ToArray)
'Listen asynchronously for another incoming message.
stream.BeginRead(buffer, 0, Me.BufferSize, AddressOf Read, New ReadAsyncState With {.client = client, .Buffer = buffer})
End If
Else
Me.RemoveClient(client)
End If
Catch ex As Exception
Me.RemoveClient(client)
Return
End Try
End Sub
What's the performance of the code below?
RaiseEvent MessageReceived(client, buffer.Take(byteCount).ToArray)
I am using 1024 as a buffer size. So the variable buffer is a byte array of size 1024. However I just need to return a buffer of size byteCount. For this, I am using Array.Take().ToArray(). Is there any better way to implement this to improve performance? Is it better to use Array.Copy or Buffer.BlockCopy?