我正在尝试编写TcpClient
实现。我想在处理数据时开始下一次读取,但我不确定何时传入BeginRead
的字节数组被修改。这是我目前的实施
private void ProcessData()
{
byte[] buffer = new byte[_tcpClient.ReceiveBufferSize];
var networkStream = _tcpClient.GetStream();
IAsyncResult result = networkStream.BeginRead(buffer, 0, buffer.Length, null, null);
int read;
while ((read = networkStream.EndRead(result)) != 0)
{
result = networkStream.BeginRead(buffer, 0, buffer.Length, null, null);
ProcessChunk(buffer, read);
}
}
我在长时间运行的函数之前启动了下一个BeginRead
因为我希望后台IO在我处理时开始获取下一个数据块。我是否可以只使用一个byte[]
缓冲区执行此操作,还是需要每隔BeginRead
次呼叫进行备用?
private void ProcessData()
{
bool bufferChoice = false;
byte[] bufferA = new byte[_tcpClient.ReceiveBufferSize];
byte[] bufferB = new byte[_tcpClient.ReceiveBufferSize];
var networkStream = _tcpClient.GetStream();
IAsyncResult result = networkStream.BeginRead(bufferA, 0, bufferA.Length, null, null);
int read;
while ((read = networkStream.EndRead(result)) != 0)
{
if (bufferChoice)
{
result = networkStream.BeginRead(bufferA, 0, bufferA.Length, null, null);
ProcessChunk(bufferB, read); //Call function with B's buffer
}
else
{
result = networkStream.BeginRead(bufferB, 0, bufferB.Length, null, null);
ProcessChunk(bufferA, read); //Call function with A's buffer
}
bufferChoice = !bufferChoice;
}
}
答案 0 :(得分:1)
通常不保证何时使用传递给BeginRead的缓冲区。从理论上讲,它甚至可以在BeginRead调用期间同步填充。
旁注:您应该编写始终正常运行的代码,因为它比推测特定实现的特定行为更容易推理。在这种情况下,只需复制数据或使用多个缓冲区,这样就不会有出色的IO和处理共享相同的缓冲区。