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);
        }
    }
01-02 17:00
查看更多