'Correct MemoryPool usage along with web sockets

I'm using a MemoryPool because it's meant to be used in cases such as this one to reduce the pressure on the GC by reusing the allocated memory rather than creating new memory blocks each time.

I've seen similar code snippets where people put MemoryPool<byte>.Shared.Rent outside the while loop and some people do that inside the loop. What is the correct way to do so?

private async Task ReceiveLoopAsync()
{
    var buffer = MemoryPool<byte>.Shared.Rent(4096);

    try
    {
        while (_clientWebSocket.State == WebSocketState.Open && !_receiveCancellationTokenSource.IsCancellationRequested)
        {
            await using var stream = _memoryStreamPool.GetStream();

            ValueWebSocketReceiveResult receiveResult;
            do
            {
                receiveResult = await _clientWebSocket.ReceiveAsync(buffer.Memory, _receiveCancellationTokenSource.Token).ConfigureAwait(false);

                if (receiveResult.MessageType == WebSocketMessageType.Close)
                {
                    break;
                }

                await stream.WriteAsync(buffer.Memory[..receiveResult.Count], CancellationToken.None).ConfigureAwait(false);
            } while (!receiveResult.EndOfMessage);

            stream.Seek(0, SeekOrigin.Begin);

            if (receiveResult.MessageType == WebSocketMessageType.Close)
            {
                break;
            }

            using var reader = new StreamReader(stream, Encoding.UTF8);
            var message = await reader.ReadToEndAsync().ConfigureAwait(false);

            MessageReceived?.Invoke(this, new MessageReceivedEventArgs(message));
        }
    }
    catch (OperationCanceledException ex) when (_receiveCancellationTokenSource.Token.IsCancellationRequested)
    {
    }
    catch (Exception ex)
    {
    }
    finally
    {
        buffer.Dispose();
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source