2
我想寫一個TcpClient
的實現。我想在我處理數據時開始下一次讀取,但我不確定何時傳入BeginRead
的字節數組被修改。這是我目前的執行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;
}
}
在我寫了關於如何做多個緩衝區的「示例代碼」之後,我意識到這很簡單,我只是改變了另一種方法。 –