From 47664b7167a8b4503658fda4ebd1201048c5e0fb Mon Sep 17 00:00:00 2001 From: Ahmad Noman Musleh Date: Mon, 28 Mar 2022 13:05:56 +0300 Subject: [PATCH] Fixed the issue with using array pool instead of allocating new array on each incoming message --- src/OpenAPI.Net/OpenAPI.Net.csproj | 2 +- src/OpenAPI.Net/OpenClient.cs | 9 +++++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/OpenAPI.Net/OpenAPI.Net.csproj b/src/OpenAPI.Net/OpenAPI.Net.csproj index 9e67c02..d7ab81b 100644 --- a/src/OpenAPI.Net/OpenAPI.Net.csproj +++ b/src/OpenAPI.Net/OpenAPI.Net.csproj @@ -9,7 +9,7 @@ cTrader, Open API, Spotware, cTrader A .NET RX library for cTrader Open API cTrader.OpenAPI.Net - 1.4.1 + 1.4.2 AnyCPU Spotware Spotware diff --git a/src/OpenAPI.Net/OpenClient.cs b/src/OpenAPI.Net/OpenClient.cs index 7bb45ab..23b983e 100644 --- a/src/OpenAPI.Net/OpenClient.cs +++ b/src/OpenAPI.Net/OpenClient.cs @@ -378,6 +378,7 @@ private async Task StartSendingMessages(CancellationToken cancellationToken) private async void ReadTcp(CancellationToken cancellationToken) { var dataLength = new byte[4]; + byte[] data = null; try { @@ -399,13 +400,13 @@ private async void ReadTcp(CancellationToken cancellationToken) if (length <= 0) continue; - var data = new byte[length]; + data = ArrayPool.Shared.Rent(length); readBytes = 0; do { - var count = data.Length - readBytes; + var count = length - readBytes; readBytes += await _sslStream.ReadAsync(data, readBytes, count, cancellationToken).ConfigureAwait(false); @@ -415,11 +416,15 @@ private async void ReadTcp(CancellationToken cancellationToken) var message = ProtoMessage.Parser.ParseFrom(data, 0, length); + ArrayPool.Shared.Return(data); + OnNext(message); } } catch (Exception ex) { + if (data is not null) ArrayPool.Shared.Return(data); + var exception = new ReceiveException(ex); OnError(exception);