2011-10-19 99 views
1

如何構造下面的代碼,以便我可以讀取塊中的所有流。 目前它一直返回相同的數據。不能前進。從流中異步反覆讀取?

public static IObservable<byte[]> AsyncRead(this Stream stream, int bufferSize) 
{ 
    var asyncRead = Observable.FromAsyncPattern<byte[], int, int, int>(stream.BeginRead, stream.EndRead); 

    var buffer = new byte[bufferSize]; 

    return asyncRead(buffer, 0, bufferSize) 
     .Select(cbRead => 
        { 
         var dataChunk = new byte[cbRead]; 

         Buffer.BlockCopy(buffer, 0, dataChunk, 0, cbRead); 

         return dataChunk; 
        }) 
     .Repeat() 
     .TakeWhile(dataChunk => dataChunk.Length > 0); 
} 

回答

1

陷入同樣的​​陷阱。異步流的行爲類似於可重放的行爲。雖然它只包含那一個項目。爲了解決這個問題,將其包裝在Defer這樣的

Observable.Defer(() => asyncRead(buffer, 0, bufferSize)) 
...