以下是我用于从NetworkStream上创建的GZipStream读取数据的AsyncCallback:
void ReadCompressedDataCallback(IAsyncResult ar)
{
var state = ar.AsyncState as ReadCompressedDataState;
try
{
switch (state.State)
{
case EReadCompressedDataState.BeginRead:
state.State = EReadCompressedDataState.EndRead;
state.InputStream.BeginRead(state.Buf, 0, state.Buf.Length, ReadCompressedDataCallback, state);
break;
case EReadCompressedDataState.EndRead:
var read = state.InputStream.EndRead(ar);
if (read==0)
{
state.OnCompleted();
return;
}
state.Result.Write(state.Buf,0,read);
state.State = EReadCompressedDataState.BeginRead;
ReadCompressedDataCallback(ar);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
catch (Exception e)
{
state.LastException = e;
state.OnCompleted();
}
}
state.InputStream
类似于新的GZipStream(NetworkStream)。
我的问题是,第一次拨打read = state.InputStream.EndRead(ar);
时,read
始终为0,并且读取停止。在调试器中,当我再次开始读取时,会读取一些数据。
根据我读过的文档,只有当没有更多的字节需要读取时,NetworkStream才会在读取时返回0个字节,但是这里返回0个字节,而下一次读取时会返回一些数据。
如何正确读取所有gzip压缩数据,而不会让应用程序“死锁”等待从未到过的数据?