`NetworkStream`是内部缓冲的吗?

问题描述 投票:0回答:1

我在想是否有必要将

NetworkStream
包裹在
BufferedStream
中连续读取,例如1字节、2字节、4字节等...我担心连续调用
ReadXxxAsync
会导致多次读取不必要的系统调用或网络 IO。

使用案例:

var stream = tcpClient.GetStream();
var buffer = new byte[4096];

await stream.ReadExactlyAsync(buffer.AsMemory(0, 1));
if (buffer[0] != ...) {
    await tcpClient.DisconnectAsync();
    return;
}

// Will this cause the 2nd time network IO operation? 
// Or only read from kernel network buffer?
await stream.ReadExactlyAsync(buffer.AsMemory(1, 2)); 
if (BinaryPrimitives.ReadUInt16BigEndian(buffer.AsSpan(1, 2)) != ...) {
    await tcpClient.DisconnectAsync();
    return;
}

// Will this cause the 3rd time network IO operation? 
await stream.ReadExactlyAsync(buffer.AsMemory(3, 2));
var messageBodyLength = BinaryPrimitives.ReadUInt16BigEndian(buffer.AsSpan(3, 2));

var messageBody = buffer.AsMemory(5, messageBodyLength);
await stream.ReadExactlyAsync(messageBody);

...
...
c# tcpclient networkstream bufferedstream
1个回答
1
投票

是的,它是缓冲的 - 如果您查看它的方法,您会发现所有

Read
Write
方法都接受缓冲区。请参阅https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.networkstream?view=net-8.0

© www.soinside.com 2019 - 2024. All rights reserved.