ByteStream异步字节访问
节省内存消耗。
/// <summary>
/// 字节流,包装流以实现高效的异步字节访问
/// </summary>
public sealed class ByteStream : IDisposable
{
private readonly Stream _stream;
private readonly byte[] _buffer;
private int _position;
private int _bufferedBytes;
public ByteStream(Stream stream)
{
_stream = stream;
_buffer = new byte[1024 * 8];
}
public async ValueTask<byte?> ReadByteAsync()
{
if (_position == _bufferedBytes)
{
_position = 0;
_bufferedBytes = await _stream.ReadAsync(_buffer, 0, _buffer.Length).ConfigureAwait(false);
if (_bufferedBytes == 0) // 流读取结束
{
return null;
}
}
return _buffer[_position++];
}
public void Dispose()
{
_stream.Dispose();
}
}
---------------------------------------------------------------------------------
byte? val = null;
using (var stream = new ByteStream(File.OpenRead("E:\\bigFile.txt")))
{
while ((val = await stream.ReadByteAsync()).HasValue)
{
ConsumeByte(val.Value);
}
}
应用场景
- a)在API中只用await;
- b)在API中避免相关的分配开销是重要的;
- c)同步完成是通用情况,能够有效的将对象池用于异步完成。