Skip to content

Commit d931926

Browse files
CopilotAArnott
andauthored
Optimize WebSocket receive path on pre-netstandard2.1 targets (#1462)
* Initial plan * Optimize netfx websocket read buffer path Co-authored-by: AArnott <3548+AArnott@users.noreply.github.com> * Limit pooled receive segment to destination memory length Co-authored-by: AArnott <3548+AArnott@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: AArnott <3548+AArnott@users.noreply.github.com>
1 parent dd89676 commit d931926

1 file changed

Lines changed: 17 additions & 7 deletions

File tree

src/StreamJsonRpc/WebSocketMessageHandler.cs

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -96,17 +96,27 @@ void IJsonRpcMessageBufferManager.DeserializationComplete(JsonRpcMessage message
9696
result = await this.WebSocket.ReceiveAsync(memory, cancellationToken).ConfigureAwait(false);
9797
this.contentSequenceBuilder.Advance(result.Count);
9898
#else
99-
ArrayPool<byte> pool = ArrayPool<byte>.Shared;
100-
byte[] segment = pool.Rent(this.sizeHint);
101-
try
99+
Memory<byte> memory = this.contentSequenceBuilder.GetMemory(this.sizeHint);
100+
if (MemoryMarshal.TryGetArray(memory, out ArraySegment<byte> segment))
102101
{
103-
result = await this.WebSocket.ReceiveAsync(new ArraySegment<byte>(segment), cancellationToken).ConfigureAwait(false);
104-
this.contentSequenceBuilder.Write(segment.AsSpan(0, result.Count));
102+
result = await this.WebSocket.ReceiveAsync(segment, cancellationToken).ConfigureAwait(false);
105103
}
106-
finally
104+
else
107105
{
108-
pool.Return(segment);
106+
ArrayPool<byte> pool = ArrayPool<byte>.Shared;
107+
byte[] rented = pool.Rent(memory.Length);
108+
try
109+
{
110+
result = await this.WebSocket.ReceiveAsync(new ArraySegment<byte>(rented, 0, memory.Length), cancellationToken).ConfigureAwait(false);
111+
rented.AsSpan(0, result.Count).CopyTo(memory.Span);
112+
}
113+
finally
114+
{
115+
pool.Return(rented);
116+
}
109117
}
118+
119+
this.contentSequenceBuilder.Advance(result.Count);
110120
#endif
111121
if (result.MessageType == WebSocketMessageType.Close)
112122
{

0 commit comments

Comments
 (0)