diff --git a/src/Opc.Ua.Bindings.Https/Https/WebSocketByteTransport.cs b/src/Opc.Ua.Bindings.Https/Https/WebSocketByteTransport.cs index 408de881dd..94e46aab84 100644 --- a/src/Opc.Ua.Bindings.Https/Https/WebSocketByteTransport.cs +++ b/src/Opc.Ua.Bindings.Https/Https/WebSocketByteTransport.cs @@ -393,6 +393,17 @@ namespace Opc.Ua.Bindings try { await m_sendLock.WaitAsync(linkedCts.Token).ConfigureAwait(false); + // SemaphoreSlim can still grant a waiter whose token was cancelled when a + // release reaches it before the cancellation removes it. A sender queued + // across Close would then write to the aborted socket and fail with the + // socket's own error, so it gives the lock back and fails as closed. + if (Volatile.Read(ref m_closed) != 0) + { + m_sendLock.Release(); + throw ServiceResultException.Create( + StatusCodes.BadConnectionClosed, + "The WebSocket transport is closed."); + } return linkedCts; } catch (OperationCanceledException) when (!ct.IsCancellationRequested) diff --git a/tests/Opc.Ua.Core.Tests/Stack/Transport/WebSocketByteTransportTests.cs b/tests/Opc.Ua.Core.Tests/Stack/Transport/WebSocketByteTransportTests.cs index f25139b708..f91123a46a 100644 --- a/tests/Opc.Ua.Core.Tests/Stack/Transport/WebSocketByteTransportTests.cs +++ b/tests/Opc.Ua.Core.Tests/Stack/Transport/WebSocketByteTransportTests.cs @@ -503,7 +503,27 @@ namespace Opc.Ua.Core.Tests.Stack.Transport /// sender forever. /// [Test] - public async Task CloseFailsQueuedSendInsteadOfOrphaningItAsync() + public Task CloseFailsQueuedSendInsteadOfOrphaningItAsync() + { + return CloseWithQueuedSendAsync(); + } + + /// + /// Close can wake the in-flight sender, whose lock release then grants + /// the queued waiter before its cancellation removes it. The queued + /// sender must still fail as closed rather than write to the aborted + /// socket. The interleaving depends on the thread pool, so it repeats. + /// + [Test] + public async Task CloseFailsQueuedSendEvenWhenTheLockIsGrantedAsync() + { + for (int iteration = 0; iteration < 2000; iteration++) + { + await CloseWithQueuedSendAsync().ConfigureAwait(false); + } + } + + private async Task CloseWithQueuedSendAsync() { using var socket = new BlockingSendWebSocket(); var transport = new WebSocketServerByteTransport(