Skip to content

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

Description

@leecampbell-codeagent

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions