From 23e2ddaa7ac60e3be43b2b4ab845bd8106157e99 Mon Sep 17 00:00:00 2001 From: Kerry Jiang Date: Sun, 29 Sep 2024 12:21:02 -0700 Subject: [PATCH] fix SemaphoreFullException in SendAsync --- .../PipeConnectionBase.cs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/SuperSocket.Connection/PipeConnectionBase.cs b/src/SuperSocket.Connection/PipeConnectionBase.cs index 976ed0cb0..c19410b57 100644 --- a/src/SuperSocket.Connection/PipeConnectionBase.cs +++ b/src/SuperSocket.Connection/PipeConnectionBase.cs @@ -166,15 +166,19 @@ private void CheckConnectionOpen() public override async ValueTask SendAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) { + var sendLockAcquired = false; + try { await SendLock.WaitAsync(cancellationToken).ConfigureAwait(false); + sendLockAcquired = true; WriteBuffer(OutputWriter, buffer); await OutputWriter.FlushAsync(cancellationToken).ConfigureAwait(false); } finally { - SendLock.Release(); + if (sendLockAcquired) + SendLock.Release(); } } @@ -186,29 +190,37 @@ private void WriteBuffer(PipeWriter writer, ReadOnlyMemory buffer) public override async ValueTask SendAsync(IPackageEncoder packageEncoder, TPackage package, CancellationToken cancellationToken = default) { + var sendLockAcquired = false; + try { await SendLock.WaitAsync(cancellationToken).ConfigureAwait(false); + sendLockAcquired = true; WritePackageWithEncoder(OutputWriter, packageEncoder, package); await OutputWriter.FlushAsync(cancellationToken).ConfigureAwait(false); } finally { - SendLock.Release(); + if (sendLockAcquired) + SendLock.Release(); } } public override async ValueTask SendAsync(Action write, CancellationToken cancellationToken) { + var sendLockAcquired = false; + try { await SendLock.WaitAsync(cancellationToken).ConfigureAwait(false); + sendLockAcquired = true; write(OutputWriter); await OutputWriter.FlushAsync(cancellationToken).ConfigureAwait(false); } finally { - SendLock.Release(); + if (sendLockAcquired) + SendLock.Release(); } }