如何构造以下代码,以便我可以读取块中的所有流。 目前它不断返回相同的数据。无法前进。
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);
}
答案 0 :(得分:1)
同样陷入同样的陷阱。异步流的行为类似于可重放的流。虽然它只包含那一项。要解决此问题,请将其包含在Defer
中,如下所示
Observable.Defer(() => asyncRead(buffer, 0, bufferSize))
...