Repository: microsoft/garnet
File: libs/common/Networking/NetworkHandler.cs (C#)

Code before:
                if (token.IsCancellationRequested) throw new TaskCanceledException("AuthenticateAsClientAsync was cancelled");

                logger?.LogDebug("Completed client TLS authentication for {remoteEndpoint}", remoteEndpointName);
                // Display the properties and settings for the authenticated stream.
                if (logger != null && logger.IsEnabled(LogLevel.Trace))
                    LogSecurityInfo(sslStream, remoteEndpointName, logger);

                // There may be extra bytes left over after auth, we need to process them (non-blocking) before returning
                var result = sslStream.ReadAsync(new Memory<byte>(transportReceiveBuffer, transportBytesRead, transportReceiveBuffer.Length - transportBytesRead), cancellationTokenSource.Token);
                _ = SslReaderAsync(result.AsTask(), cancellationTokenSource.Token);
            }
            catch (Exception ex)
            {
                logger?.LogWarning(ex, "An error has occurred");
                readerStatus = TlsReaderStatus.Rest;
                if (expectingData.CurrentCount == 0) expectingData.Release();
                Dispose();
                throw;
            }
        }

        /// <summary>
        /// On network receive
        /// </summary>
        /// <param name="bytesTransferred">Number of bytes transferred</param>
        public async Task OnNetworkReceiveAsync(int bytesTransferred)
        {
            // Wait for SslStream async processing to complete, if any (e.g., authentication phase)
            while (readerStatus == TlsReaderStatus.Active)
                await expectingData.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);

            // Increment network bytes read
            networkBytesRead += bytesTransferred;

            switch (readerStatus)
            {
                case TlsReaderStatus.Rest:
                    // Synchronously try to process the received data
                    if (sslStream == null)
                    {
                        transportReceiveBuffer = networkReceiveBuffer;
                        unsafe
                        {
                            transportReceiveBufferPtr = networkReceiveBufferPtr;
                        }
                        transportBytesRead = networkBytesRead;

                        // We do not have an active read task, so we will process on the network thread
                        Process();
                    }
                    else

Review comment (performance):
Using `Task` here will cause a class instance allocation per call, which is very expensive. It seems even the non-TLS paths will cause this. We should use the `ValueTask` struct here.

Code after:
                if (token.IsCancellationRequested) throw new TaskCanceledException("AuthenticateAsClientAsync was cancelled");

                logger?.LogDebug("Completed client TLS authentication for {remoteEndpoint}", remoteEndpointName);
                // Display the properties and settings for the authenticated stream.
                if (logger != null && logger.IsEnabled(LogLevel.Trace))
                    LogSecurityInfo(sslStream, remoteEndpointName, logger);

                // There may be extra bytes left over after auth, we need to process them (non-blocking) before returning
                var result = sslStream.ReadAsync(new Memory<byte>(transportReceiveBuffer, transportBytesRead, transportReceiveBuffer.Length - transportBytesRead), cancellationTokenSource.Token);
                _ = SslReaderAsync(result.AsTask(), cancellationTokenSource.Token);
            }
            catch (Exception ex)
            {
                logger?.LogWarning(ex, "An error has occurred");
                readerStatus = TlsReaderStatus.Rest;
                if (expectingData.CurrentCount == 0) expectingData.Release();
                Dispose();
                throw;
            }
        }

        public unsafe void OnNetworkReceiveWithoutTLS(int bytesTransferred)
        {
            networkBytesRead += bytesTransferred;
            transportReceiveBuffer = networkReceiveBuffer;
            transportReceiveBufferPtr = networkReceiveBufferPtr;
            transportBytesRead = networkBytesRead;

            // Process non-TLS code on the synchronous thread
            Process();

            EndTransformNetworkToTransport();
            UpdateNetworkBuffers();
        }

        /// <summary>
        /// On network receive
        /// </summary>
        /// <param name="bytesTransferred">Number of bytes transferred</param>
        public async ValueTask OnNetworkReceiveWithTLSAsync(int bytesTransferred)
        {
            // Wait for SslStream async processing to complete, if any (e.g., authentication phase)
            while (readerStatus == TlsReaderStatus.Active)
                await expectingData.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);

            // Increment network bytes read
            networkBytesRead += bytesTransferred;

            switch (readerStatus)
            {
                case TlsReaderStatus.Rest: