Memory/ReadOnlyMemory 模拟:零复制窗口
使用 ArraySegment 代替数组传递数据:创建窗口,实现 Skip/Take/Slice,解析标头和有效载荷,并只在边界处复制。
Memory/ReadOnlyMemory 模拟:零复制窗口 是 CoddyKit 上的免费 C# Academy 课时。 这是第 2 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 C# Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 C# Academy 课程共包含 3 节课。
数组上的窗口
目标:将数组视为内存窗口。
- 使用ArraySegment<T>传递视图
- 构建小型的跳过/提取/切片辅助方法
- 无副本地解析标头和负载
- 只在输入输出边界处复制
跳过/提取/切片辅助方法
创建小型的切片、跳过和提取辅助方法,以便清晰地组合窗口。
using System;
public static class Seg
{
public static ArraySegment<T> Slice<T>(ArraySegment<T> s, int start, int count)
{
if (start < 0 || count < 0 || start + count > s.Count) throw new ArgumentOutOfRangeException();
return new ArraySegment<T>(s.Array, s.Offset + start, count);
}
public static ArraySegment<T> Skip<T>(ArraySegment<T> s, int n)
{
if (n < 0 || n > s.Count) throw new ArgumentOutOfRangeException("n");
return new ArraySegment<T>(s.Array, s.Offset + n, s.Count - n);
}
public static ArraySegment<T> Take<T>(ArraySegment<T> s, int n)
{
if (n < 0 || n > s.Count) throw new ArgumentOutOfRangeException("n");
return new ArraySegment<T>(s.Array, s.Offset, n);
}
}
public class Program
{
public static void Main(string[] args)
{
int[] xs = new int[] { 10, 20, 30, 40, 50 };
ArraySegment<int> view = new ArraySegment<int>(xs, 1, 3); // 20,30,40
ArraySegment<int> head = Seg.Take<int>(view, 2); // 20,30
ArraySegment<int> tail = Seg.Skip<int>(view, 1); // 30,40
Console.WriteLine(head.Array[head.Offset] + "," + head.Array[head.Offset + 1]);
Console.WriteLine(tail.Array[tail.Offset] + "," + tail.Array[tail.Offset + 1]);
}
}
窗口间复制
使用缓冲区.BlockCopy在窗口之间移动数据,而无需创建新数组。
using System;
public static class SegCopy
{
public static int Copy(ArraySegment<byte> src, ArraySegment<byte> dst)
{
int n = src.Count < dst.Count ? src.Count : dst.Count;
Buffer.BlockCopy(src.Array, src.Offset, dst.Array, dst.Offset, n);
return n;
}
}
public class Program
{
public static void Main(string[] args)
{
byte[] a = new byte[] { 1, 2, 3, 4, 5, 6 };
byte[] b = new byte[] { 0, 0, 0, 0, 0, 0 };
ArraySegment<byte> winA = new ArraySegment<byte>(a, 2, 3); // 3,4,5
ArraySegment<byte> winB = new ArraySegment<byte>(b, 1, 3); // target
int copied = SegCopy.Copy(winA, winB);
Console.WriteLine("Copied: " + copied);
Console.WriteLine(string.Join(",", b)); // 0,3,4,5,0,0
}
}
标头+负载解析
根据偏移量进行解析,并创建负载窗口。仅在需要时将其转换为文本。
using System;
using System.Text;
public static class Parser
{
// Message layout: [len:2 bytes little-endian][type:1 byte][payload:len bytes]
public static void Parse(ArraySegment<byte> msg)
{
if (msg.Count < 3) throw new ArgumentException("message too short");
int o = msg.Offset;
byte[] arr = msg.Array;
int len = arr[o] | (arr[o + 1] << 8); // ushort little-endian
byte typ = arr[o + 2];
ArraySegment<byte> payload = new ArraySegment<byte>(arr, o + 3, len);
Console.WriteLine("Type=" + typ + " Len=" + len);
// Materialize only at the boundary (to string for display)
string text = Encoding.ASCII.GetString(payload.Array, payload.Offset, payload.Count);
Console.WriteLine("Payload: " + text);
}
}
public class Program
{
public static void Main(string[] args)
{
// Build: len=5 ("Hello"), type=42
byte[] buf = new byte[3 + 5];
buf[0] = 5; buf[1] = 0; buf[2] = 42;
byte[] hello = Encoding.ASCII.GetBytes("Hello");
Buffer.BlockCopy(hello, 0, buf, 3, 5);
Parser.Parse(new ArraySegment<byte>(buf, 0, buf.Length));
}
}
按约定只读
在 C# 6 中,使用 ArraySegment 实现只读行为是一种约定:承诺只读取的方法绝不能修改数据。
using System;
public static class Checksums
{
// Treat the segment as "read-only": never write to seg.Array here.
public static int SumBytes(ArraySegment<byte> seg)
{
int end = seg.Offset + seg.Count;
int total = 0;
for (int i = seg.Offset; i < end; i++) total += seg.Array[i];
return total & 0xFF;
}
}
public class Program
{
public static void Main(string[] args)
{
byte[] data = new byte[] { 10, 20, 30, 40, 50 };
ArraySegment<byte> window = new ArraySegment<byte>(data, 1, 3); // 20,30,40
int checksum = Checksums.SumBytes(window);
Console.WriteLine("Checksum = " + checksum);
}
}
在边界处复制
只在边缘处复制(发送到其他层、记录日志或存储)。保持内部步骤为零拷贝。
using System;
public static class Materialize
{
public static T[] ToArray<T>(ArraySegment<T> s)
{
T[] copy = new T[s.Count];
Array.Copy(s.Array, s.Offset, copy, 0, s.Count);
return copy;
}
}
public class Program
{
public static void Main(string[] args)
{
int[] data = new int[] { 5, 6, 7, 8, 9 };
ArraySegment<int> middle = new ArraySegment<int>(data, 1, 3); // 6,7,8
int[] copy = Materialize.ToArray<int>(middle); // copy at boundary
Console.WriteLine(string.Join(",", copy));
}
}
窗口的作用
回顾
回顾:将ArraySegment<T>用作类似内存的窗口。使用跳过/提取/切片进行组合,按偏移量解析,并仅在必须时复制。
常见问题解答
「Memory/ReadOnlyMemory 模拟:零复制窗口」课时是免费的吗?
是的 — 「Memory/ReadOnlyMemory 模拟:零复制窗口」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 C# Academy 课程的其余内容,请升级到 CoddyKit PRO。 C# Academy 课程共包含 3 节课。
「Memory/ReadOnlyMemory 模拟:零复制窗口」这节课中我会学到什么?
使用 ArraySegment 代替数组传递数据:创建窗口,实现 Skip/Take/Slice,解析标头和有效载荷,并只在边界处复制。 你通过在浏览器中直接运行的动手代码来练习 C# Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 C# Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 C# Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 3 节。
「Memory/ReadOnlyMemory 模拟:零复制窗口」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 C# Academy 课中编写并运行代码吗?
能。每节 C# Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- Span/ReadOnlySpan 基础(C# 6 模拟)
- Memory/ReadOnlyMemory 模拟:零复制窗口
- 字符串即 Span 的 API(C# 6 模拟)