.NET 框架中的 Span<T> 和流

我正在使用网络缓冲区和流,Span 和 Memory 非常适合应用程序要求。

根据这个问题,我想让一个 Stream 接受 Span 作为参数。我知道这是在 .NET Core 2.1 中实现的,但我想知道是否有办法在 .NET Framework 中获得此功能?(我使用的是 4.7.1)

就像是:

Span<Byte> buffer = new Span<byte>();
stream.Read(buffer);


MM们
浏览 266回答 3
3回答

莫回无

我设法通过为 Stream 类编写扩展方法并实现 .NET Core 处理 Span 的默认行为来解决这个问题。&nbsp; &nbsp; public static int Read(this Stream thisStream, Span<byte> buffer)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length);&nbsp; &nbsp; &nbsp; &nbsp; try&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int numRead = thisStream.Read(sharedBuffer, 0, buffer.Length);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ((uint)numRead > (uint)buffer.Length)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new IOException(SR.IO_StreamTooLong);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new Span<byte>(sharedBuffer, 0, numRead).CopyTo(buffer);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return numRead;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; finally { ArrayPool<byte>.Shared.Return(sharedBuffer); }&nbsp; &nbsp; }和&nbsp; &nbsp; public static void Write(this Stream thisStream, ReadOnlySpan<byte> buffer)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length);&nbsp; &nbsp; &nbsp; &nbsp; try&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; buffer.CopyTo(sharedBuffer);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; thisStream.Write(sharedBuffer, 0, buffer.Length);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; finally { ArrayPool<byte>.Shared.Return(sharedBuffer); }&nbsp; &nbsp; }

郎朗坤

不幸的是,由于此功能尚未在 .Net Standard 中实现,因此未包含在 .Net Framework 中。编辑:我记得我从某处读到有可以与.Net Framework 一起使用的预发布NuGet 包检查 NuGetSystem.Memory

扬帆大鱼

公认的解决方案效果很好!但是,在某些情况下,我同时使用面向 .NET Core 和 .NET Framework 的共享项目,我同时使用数组和Span<T>:var _buffer = new byte[1024*1024];Span<Byte> buffer = _buffer;#if NETCOREAPP3_1stream.Read(buffer);#elsestream.Read(_buffer);#endif通过这种方式,我可以避免从 ArrayPool 租用/复制/返回数组的小开销。
打开App,查看更多内容
随时随地看视频慕课网APP