Skip to content

fix: prevent ObjectDisposedException when StopAsync races disposal - #172

Merged
steingran merged 2 commits into
mainfrom
claude/github-issue-171-609b5a
Nov 19, 2026
Merged

steingran merged 2 commits into
mainfrom
claude/github-issue-171-609b5a

Conversation

@steingran

Copy link
Copy Markdown
Owner

Fixes #171

Problem

LeaderElectionService.StopAsync could throw ObjectDisposedException from SemaphoreSlim when Dispose/DisposeAsync ran at the same time, for example when a WebApplicationFactory is disposed at the end of an integration test. StopAsync checked the disposed flag without holding the lock, and DisposeAsync disposed stateLock without waiting for StopAsync. StartAsync, TryAcquireLeadershipAsync and ReleaseLeadershipAsync had the same gap.

Changes

  • Disposal waits for all operations that use the lock. The callback counter (activeCallbacks, now activeOperations) also covers StopAsync, StartAsync, TryAcquireLeadershipAsync and ReleaseLeadershipAsync, not only timer callbacks.
  • No gap between the check and the use. TryEnterOperation increments the counter before it checks the disposed flag. DisposeAsync sets the flag with Interlocked.Exchange. Both are full fences, so either the operation sees the flag and backs out, or disposal sees the counter and waits. The atomic flag also means that only the first of several concurrent dispose calls runs the disposal body.
  • StopAsync never throws on shutdown. After disposal it returns without doing anything. If disposal gives up after its 10-second timeout and disposes the lock or the cancellation token source, StopAsync catches the ObjectDisposedException and treats the service as stopped.
  • Other public methods keep their contract. After disposal they still throw ObjectDisposedException, but it now names LeaderElectionService, not the internal SemaphoreSlim.
  • Timer fixes found along the way:
    • StopAsync and DisposeAsync could both dispose the same timer field and set it to null, which could cause a NullReferenceException. DisposeTimerAsync now takes the timer out of its field with Interlocked.Exchange before disposing it.
    • An operation that disposal waited for could start a new timer (for example, ReleaseLeadershipAsync restarts the election timer), and nothing disposed it. Disposal now clears both timers again after the wait.

Tests

New StopDisposeRaceTests:

  • StopAsync and DisposeAsync run at the same time, 50 iterations, alternating which starts first. The same test with sync Dispose().
  • DisposeAsync waits for a StopAsync that is releasing leadership.
  • StopAsync after disposal does not throw.
  • Public methods called during disposal only throw ObjectDisposedException naming the service.

Against the original code, all four race tests fail. The two StopAsync/dispose tests fail with the stack trace from the issue, from SemaphoreSlim.Release in StopAsync. With the fix, all 613 unit tests passed in 16 of 16 runs across net8.0 and net10.0.

Notes for reviewers

  • The new tests are in a collection that does not run in parallel with other tests. Without this, their load made the timing-sensitive MultiInstanceLeaderElectionTests.LeaderFailover_ShouldElectNewLeader fail in about 1 of 3 full runs. That test passed every time without the new tests, on both the original and the fixed code, so the failures did not come from the fix.
  • The 10-second dispose timeout is unchanged.
  • Integration tests were not run locally; they need the external services.

StopAsync checked the disposed flag without holding the lock and then
waited on stateLock, while DisposeAsync disposed stateLock without
waiting for StopAsync. At host shutdown this could throw
ObjectDisposedException from SemaphoreSlim.

- Count StopAsync, StartAsync, TryAcquireLeadershipAsync,
  ReleaseLeadershipAsync and timer callbacks as in-progress operations.
  Each operation increments the counter before it checks the disposed
  flag, so DisposeAsync either waits for it or the operation backs out.
- Set the disposed flag atomically so only the first dispose call runs.
- StopAsync returns quietly after disposal and treats an
  ObjectDisposedException after the dispose timeout as stopped.
- Take timers out of their fields atomically before disposing them, and
  dispose any timer started by an operation that disposal waited for.
- Add StopDisposeRaceTests, run in a non-parallel collection.

Fixes #171
@codecov

codecov Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.00000% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 73.16%. Comparing base (ca22cd9) to head (65a471e).

Files with missing lines Patch % Lines
src/MultiLock/LeaderElectionService.cs 95.00% 0 Missing and 4 partials ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #172      +/-   ##
==========================================
+ Coverage   72.53%   73.16%   +0.62%     
==========================================
  Files          65       65              
  Lines        4974     4982       +8     
  Branches      607      603       -4     
==========================================
+ Hits         3608     3645      +37     
+ Misses       1155     1133      -22     
+ Partials      211      204       -7     
Files with missing lines Coverage Δ
src/MultiLock/LeaderElectionService.cs 81.87% <95.00%> (+8.78%) ⬆️

... and 1 file with indirect coverage changes


Continue to review full report in Codecov by Harness.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update ca22cd9...65a471e. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Codecov reported 81% patch coverage on the fix for #171. The largest gap
was the path where DisposeAsync stops waiting after its timeout, which
had no test because the timeout was a fixed 10 seconds.

- Add an internal DisposeWaitTimeout (default 10 s) so tests can use a
  short timeout. Behaviour is unchanged.
- Simplify EnterOperationOrThrow to a single ThrowIf call, which removes
  an unreachable line.
- Test that StopAsync does not throw when DisposeAsync times out and
  disposes the lock while StopAsync still holds it.
- Test StopAsync when the provider fails to release leadership,
  ReleaseLeadershipAsync when not leader, and loss of leadership after a
  failed heartbeat.
@steingran
steingran merged commit 9e42283 into main Nov 19, 2026
7 checks 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.

StopAsync can throw ObjectDisposedException when DisposeAsync runs at the same time

1 participant