我想读取称重机插座并在 GUI 中更新其值。
套接字将连续发送当前的重量值。我的数据(重量)将小于 100 字节。
如果我将缓冲区设置为 100,则它需要花费太多时间来更新当前值,因为它必须读取所有剩余的字节。因此,我将缓冲区大小更改为 4096 字节。现在该值正在实时更新。
我的问题是,
--- 提供 4096 字节真的是性能上的巨大开销(与 100 字节相比)?
--- 是否可以清除所有可用数据并在收到消息时仅读取最后 100 个字节?
我用于回调的代码:
private void ReceiveCallback(IAsyncResult ar)
{
try
{
//Get received bytes count
var bytesRead = _clientSocket.EndReceive(ar);
if (bytesRead > 0)
{
//Copy received bytes to a new byte array
var receivedBytes = new byte[ReceiveBufferSize];
Array.Copy(_buffer, 0, receivedBytes, 0, 100); //100 byte is enough for checking the data
FormatAndUpdateGUI(receivedBytes);
}
else
{
throw new Exception("Error in Reading");
}
//Read more bytes
_clientSocket.BeginReceive(_buffer, 0, _buffer.Length, 0, new AsyncCallback(ReceiveCallback), null);
}
catch (Exception ex)
{
throw new Exception("Error in Reading");
}
}