WriterReaderPhaser.FlipPhase - Task.Yield().GetAwaiter().GetResult() is a Thread Pool Anti-Pattern

Open Beginner friendly
#144 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
68/100
Issue type
Refactor
Clarity
Clearly specified
Activity status
Stale
Tech stack
csharp
Domain
performance

Research direction

Start in Utilities/WriterReaderPhaser.cs and inspect FlipPhase, especially the synchronous Task.Yield() wait and its caughtUp loop. Compare the existing behavior with the issue's SpinWait approach, then run the repository's existing test suite to verify phase flipping still completes correctly.

Written by the indexing model from the issue text.

Description

agent enhancement

File: Utilities/WriterReaderPhaser.cs

The spin-wait in FlipPhase uses:

Task.Yield().GetAwaiter().GetResult();

This is a synchronous block on an async yield — it queues the continuation back to the thread pool and then blocks the calling thread waiting for it, which is deeply counterproductive. The right approach for a spin-wait that wants to yield CPU time is:

// Prefer SpinWait for short-duration waits
var spinner = new SpinWait();
do {
    spinner.SpinOnce(); // handles Thread.Yield / Thread.Sleep(0) / Thread.Sleep(1) progression automatically
    caughtUp = isNextPhaseEven 
        ? (_oddEndEpoch == startValueAtFlip) 
        : (_evenEndEpoch == startValueAtFlip);
} while (!caughtUp);

SpinWait is purpose-built for exactly this pattern and uses adaptive backoff — it spins on CPU first, then Thread.Yield(), then Thread.Sleep(1), automatically.

Dominant language
C#
Stars
185
Forks
31
PR merge metrics
No merged PRs in 30d

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from HdrHistogram/HdrHistogram.NET

All issues in HdrHistogram/HdrHistogram.NET

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.