我正在用.NET编写高性能套接字应用程序。我有以下代码异步读取套接字。
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
以下代码的性能如何?
RaiseEvent MessageReceived(client, buffer.Take(byteCount).ToArray)
我使用1024作为缓冲区大小。所以变量 buffer 是一个大小为1024的字节数组。但是我只需要返回一个大小为 byteCount 的缓冲区。为此,我使用Array.Take()。ToArray()。有没有更好的方法来实现这一点来提高性能?使用Array.Copy或Buffer.BlockCopy是否更好?
答案 0 :(得分:1)
我认为这是你遇到的问题。如果你需要高性能,我会看SocketAsyncEventArgs。此外,提升事件将阻止您的线程,直到事件完成。我会有两个线程,一个从套接字读取并将数据放入队列。另一个从队列中读取数据并对其进行处理。