2012-10-24 2 views
2

TcpClient 구현을 작성하려고합니다. 내 데이터를 처리하는 동안 다음 읽기 시작 싶었지만 바이트 배열 BeginRead 전달 될 때 확실하지 오전 수정되었습니다. 여기에 내가 IO 내가 처리하는 동안 데이터의 다음 청크를 받기 시작하는 배경을 원했기 때문에 나는 장기 실행 기능하기 전에 다음 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); 
    } 
} 

입니다. 하나의 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; 
    } 
} 

답변

1

BeginRead에 전달 된 버퍼가 사용될 때 일반적으로 보장 할 수 없습니다. 이론적으로 BeginRead 호출 중에 동 기적으로 채워질 수도 있습니다.

사이드 노트 : 특정 구현의 특정 동작을 추측하는 것보다 추론하기가 쉽기 때문에 항상 올바르게 작동하는 코드를 작성해야합니다. 이 경우 단순히 데이터를 복사하거나 여러 버퍼를 사용하여 IO가없고 처리가 동일한 버퍼를 공유하지 마십시오.

+0

여러 개의 버퍼를 수행하는 방법에 대한 "예제 코드"를 작성한 후 간단하게 다른 방법으로 변경 한 것을 알았습니다. –

관련 문제