C# 高性能 Stream 处理

2022年10月18日 2318点热度 0人点赞 0条评论
内容目录

可复用Stream

需要安装 Microsoft.IO.RecyclableMemoryStream


    internal class StreamHandler
    {
        // Stream pool
        private static readonly RecyclableMemoryStreamManager Manager = new();

        private readonly RecyclableMemoryStream _stream;
        private volatile bool _disposed;

        public Stream Stream => _stream;

        public ResponseHandler()
        {
            _stream = (Manager.GetStream() as RecyclableMemoryStream)!;
        }

        public ReadOnlySequence<byte> GetReadOnlySequence() => _stream.GetReadOnlySequence();

        public void Dispose()
        {
            if (_disposed) return;
            _disposed = true;
            _stream.Dispose();
            GC.SuppressFinalize(this);
        }

        public ValueTask DisposeAsync()
        {
            if (_disposed) return ValueTask.CompletedTask;
            _disposed = true;
            return _stream.DisposeAsync();
        }

        public ValueTask InvokeAsync()
        {
            return ValueTask.CompletedTask;
        }

        ~ResponseHandler()
        {
            Dispose();
        }
    }

PipeReader 和 PipeWriter

需要引入 System.IO.Pipelines
更加方便地操作字节数组。

        Stream stream = .... ....

        ReadOnlySequence<byte> sequence;
        PipeReader pipeReader = PipeReader.Create(stream, new StreamPipeReaderOptions(bufferSize: Environment.SystemPageSize));
            var result = await pipeReader.ReadAsync();
            sequence = result.Buffer;

        var ex = new Exception();
        if (pipeReader != null)
        {
            await pipeReader.CompleteAsync(ex);
        }

痴者工良

高级程序员劝退师

文章评论