@@ -377,32 +377,29 @@ private async Task StartSendingMessages(CancellationToken cancellationToken)
377377 /// <returns>Task</returns>
378378 private async void ReadTcp ( CancellationToken cancellationToken )
379379 {
380- var lengthArray = new byte [ sizeof ( int ) ] ;
380+ var dataLength = new byte [ 4 ] ;
381381
382382 try
383383 {
384384 while ( ! IsDisposed )
385385 {
386-
387386 var readBytes = 0 ;
388387
389388 do
390389 {
391- var count = lengthArray . Length - readBytes ;
390+ var count = dataLength . Length - readBytes ;
392391
393- readBytes += await _sslStream . ReadAsync ( lengthArray , readBytes , count , cancellationToken ) . ConfigureAwait ( false ) ;
392+ readBytes += await _sslStream . ReadAsync ( dataLength , readBytes , count , cancellationToken ) . ConfigureAwait ( false ) ;
394393
395- if ( readBytes == 0 ) new InvalidOperationException ( "Remote host closed the connection" ) ;
394+ if ( readBytes == 0 ) throw new InvalidOperationException ( "Remote host closed the connection" ) ;
396395 }
397- while ( readBytes < lengthArray . Length ) ;
398-
399- Array . Reverse ( lengthArray ) ;
396+ while ( readBytes < dataLength . Length ) ;
400397
401- var length = BitConverter . ToInt32 ( lengthArray , 0 ) ;
398+ var length = GetLength ( dataLength ) ;
402399
403400 if ( length <= 0 ) continue ;
404401
405- var data = ArrayPool < byte > . Shared . Rent ( length ) ;
402+ var data = new byte [ length ] ;
406403
407404 readBytes = 0 ;
408405
@@ -412,20 +409,15 @@ private async void ReadTcp(CancellationToken cancellationToken)
412409
413410 readBytes += await _sslStream . ReadAsync ( data , readBytes , count , cancellationToken ) . ConfigureAwait ( false ) ;
414411
415- if ( readBytes == 0 ) new InvalidOperationException ( "Remote host closed the connection" ) ;
412+ if ( readBytes == 0 ) throw new InvalidOperationException ( "Remote host closed the connection" ) ;
416413 }
417414 while ( readBytes < length ) ;
418415
419416 var message = ProtoMessage . Parser . ParseFrom ( data , 0 , length ) ;
420417
421- ArrayPool < byte > . Shared . Return ( data ) ;
422-
423418 OnNext ( message ) ;
424419 }
425420 }
426- catch ( Exception ex ) when ( ex is OperationCanceledException )
427- {
428- }
429421 catch ( Exception ex )
430422 {
431423 var exception = new ReceiveException ( ex ) ;
@@ -434,6 +426,20 @@ private async void ReadTcp(CancellationToken cancellationToken)
434426 }
435427 }
436428
429+ /// <summary>
430+ /// Returns the length of a received message without causing extra allocation
431+ /// </summary>
432+ /// <param name="lengthBytes">The byte arrary of received lenght data</param>
433+ /// <returns>int</returns>
434+ private int GetLength ( byte [ ] lengthBytes )
435+ {
436+ var lengthSpan = lengthBytes . AsSpan ( ) ;
437+
438+ lengthSpan . Reverse ( ) ;
439+
440+ return BitConverter . ToInt32 ( lengthSpan ) ;
441+ }
442+
437443 /// <summary>
438444 /// Writes the message bytes to TCP stream
439445 /// </summary>
0 commit comments