Skip to content

fix: Close() no longer waits the full 5 s close timeout - #17

Merged
RobertPoienar merged 2 commits into
masterfrom
claude/fix-client-close-wait-4c6b1b
Nov 13, 2026
Merged

RobertPoienar merged 2 commits into
masterfrom
claude/fix-client-close-wait-4c6b1b

Conversation

@rucindrea

@rucindrea rucindrea commented Nov 13, 2026 •

Copy link
Copy Markdown

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 (in ClientWebSocket and ServerWebSocket):

  1. saves receivingExitedEvent into receivingExitedForLater,
  2. calls ReleaseCommonResources(false), which does not dispose the event but sets the field receivingExitedEvent = null,
  3. calls CloseHandshake(...), which waits up to waitTime on the saved event.

When the peer's close reply arrived, ReceiveLoop called receivingExitedEvent?.Set() on the field, which was already null. The saved event was never signalled, so Close() always timed out and reported WasClean = 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

ReceiveLoop now keeps its own references to the stream and to the event that startReceiving created, so the close sequence clearing those fields no longer affects it. While a local close is in progress (state Closed), 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 calls Set after the close sequence has stopped waiting and disposed the event, the ObjectDisposedException is 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.

ReceiveLoop is in the shared WebSocket base class, so this also fixes the wait in the server-side close paths.

Timings

tools/CloseTiming is a small console harness (net8.0). It times ClientWebSocket.Close() against a System.Net WebSocket 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 case Close() must wait about 300 ms for the real reply. Run it with:

dotnet run -c Release --project tools/CloseTiming -- 5

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() WasClean
before (master) 5,005–5,009 ms False
after 0–3 ms True
after, data frame then close reply 300 ms later 301–302 ms True

Measured locally on 13 November 2026 (EET).

dotnet build websocket-sharp/websocket-sharp-netstandard/altwebsocket-sharp.csproj -c Release builds netstandard2.0, net6.0 and net7.0 with 0 errors.

AltServer test suite

I copied AltServer (development, f4a5c33) to a scratch folder and replaced only AltServer.Tests/altwebsocket-sharp.dll with this PR's netstandard2.0 build. The tests were unchanged. dotnet test passed 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_ClosedAfterGraceTimeout takes 5.0 s and TestAllLicenseOldSdk_EngineProbeTimesOut_FailsClosed takes 3.5 s. CI wasn't rerun. It only gets faster once AltServer's checked-in dll is updated.

Not in this PR

  • VersionPrefix stays at 1.0.9. release.yml pushes a hardcoded AltWebSocketSharp.1.0.9.nupkg, so a release will need the version bumped in both places.
  • The dll copies in other repos (C# driver NuGet reference, Unity SDK altwebsocket-sharp.dll, AltServer.Tests/altwebsocket-sharp.dll) are not updated.
  • Separate issue found while testing: a server-side close (ServerWebSocket.PerformCloseSequence / PerformCloseSessionSequence) is fast, but only because ReleaseServerResources() runs closeContext() 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.

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.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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

Comment thread tools/CloseTiming/Program.cs Resolved
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
RobertPoienar merged commit 32ab922 into master Nov 13, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants