Repository navigation
fix: Close() no longer waits the full 5 s close timeout - #17
Merged
Merged
Conversation
The close sequence saves receivingExitedEvent, clears the field via ReleaseCommonResources(false), then waits on the saved event in CloseHandshake. The receive loop signalled the field, which was already null, so the waiting Close() was never woken and always waited out waitTime (5 s on the client). The receive loop now signals the event it was started with. A late Set after the close sequence has given up and disposed the event is ignored. Adds tools/CloseTiming, a console harness that times a client Close() against a System.Net server that answers the close frame, and a server-side session close. Before: ~5,005 ms, WasClean=False. After: 0-3 ms, WasClean=True.
There was a problem hiding this comment.
🟡 Changes recommended
An in-flight data frame can falsely mark a local close as clean without a peer close reply, and the timing tool leaves received close frames unanswered.
2 open issues
What changed in this PR
This PR addresses unnecessary close-timeout waits in the shared WebSocket receive loop, aiming to speed up client shutdown and downstream AltServer tests without changing resource-release ordering.
Changes:
- Passes the original completion event through receive-loop callbacks so closing can still be signalled after the field is cleared.
- Handles signalling after the event has been disposed.
- Adds a .NET 8 timing harness for client and server-session closes, with timing limits and a client clean-close check.
| File | Description |
|---|---|
websocket-sharp/websocket-sharp/WebSocket.cs |
Preserves the receive-loop completion event and guards against late signalling. |
tools/CloseTiming/Program.cs |
Measures close latency against System.Net WebSocket peers. |
tools/CloseTiming/CloseTiming.csproj |
Defines the .NET 8 harness and references the library project. |
Review effort: Balanced
Review feedback on the first fix: the receive loop signalled the receivingExited event whenever the state was Closed. A data frame still in flight during a local close therefore woke CloseHandshake, which reported WasClean = true without the peer's close reply. The loop now keeps its own stream reference and, while a local close is in progress, discards frames until a close frame arrives. A read failure after the close sequence has closed the stream is logged at Debug instead of being reported as a fatal error. CloseTiming now answers server close frames itself (System.Net's ReceiveAsync does not) and adds a case where the server sends a data frame and replies to the close 300 ms later. The previous commit returned in 0 ms with WasClean = true; this one waits about 300 ms for the real reply.
RobertPoienar
approved these changes
Nov 13, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


Cause
Every
ClientWebSocket.Close()took the full close timeout (5 s on the client). This also makes each C#AltDriver.Stop()take 5 s, and it slows down AltServer's test suite.PerformCloseSequence(inClientWebSocketandServerWebSocket):receivingExitedEventintoreceivingExitedForLater,ReleaseCommonResources(false), which does not dispose the event but sets the fieldreceivingExitedEvent = null,CloseHandshake(...), which waits up towaitTimeon the saved event.When the peer's close reply arrived,
ReceiveLoopcalledreceivingExitedEvent?.Set()on the field, which was already null. The saved event was never signalled, soClose()always timed out and reportedWasClean = false.Upstream sta/websocket-sharp avoids this by running the handshake before it releases resources. Our fork changed that order in 66a0ecb (June 2023, "Update websocket to other fork with stackoverflow fix").
Fix
ReceiveLoopnow keeps its own references to the stream and to the event thatstartReceivingcreated, so the close sequence clearing those fields no longer affects it. While a local close is in progress (stateClosed), the loop discards frames until the peer's close frame arrives, and only then signals the event. A data frame still in flight is not taken as the close reply. If the loop callsSetafter the close sequence has stopped waiting and disposed the event, theObjectDisposedExceptionis ignored. A read failure after the close sequence has closed the stream is logged at Debug, not reported as a fatal error. The close order and the existing guards against concurrent close and dispose are unchanged.ReceiveLoopis in the sharedWebSocketbase class, so this also fixes the wait in the server-side close paths.Timings
tools/CloseTimingis a small console harness (net8.0). It timesClientWebSocket.Close()against aSystem.NetWebSocket server that answers the close frame, and it also times a server-side session close. A third case has the server send a data frame and reply to the close 300 ms later. In that caseClose()must wait about 300 ms for the real reply. Run it with:It exits with 1 if a close takes 1 s or longer, if a client close is not clean, or if
Close()returns before the delayed close reply.ClientWebSocket.Close()WasCleanMeasured locally on 13 November 2026 (EET).
dotnet build websocket-sharp/websocket-sharp-netstandard/altwebsocket-sharp.csproj -c Releasebuilds netstandard2.0, net6.0 and net7.0 with 0 errors.AltServer test suite
I copied AltServer (
development, f4a5c33) to a scratch folder and replaced onlyAltServer.Tests/altwebsocket-sharp.dllwith this PR's netstandard2.0 build. The tests were unchanged.dotnet testpassed all 133 tests in 1 min 12 s (1 min 13 s after the review fix). Before this fix the suite took about 11.7 min locally and about 17.5 min in CI. The slowest tests left are deliberate timeouts:TestNonHandshakeSdk_ClosedAfterGraceTimeouttakes 5.0 s andTestAllLicenseOldSdk_EngineProbeTimesOut_FailsClosedtakes 3.5 s. CI wasn't rerun. It only gets faster once AltServer's checked-in dll is updated.Not in this PR
VersionPrefixstays at 1.0.9.release.ymlpushes a hardcodedAltWebSocketSharp.1.0.9.nupkg, so a release will need the version bumped in both places.altwebsocket-sharp.dll,AltServer.Tests/altwebsocket-sharp.dll) are not updated.ServerWebSocket.PerformCloseSequence/PerformCloseSessionSequence) is fast, but only becauseReleaseServerResources()runscloseContext()and drops the TCP connection before the close frame is sent. The client then sees an unexpected EOF instead of a close frame. This PR does not change that.