Skip to content

[Regression] BackgroundService.StartAsync may never invoke ExecuteAsync when the service is stopped immediately after start (regression from Task.Run(delegate, stoppingToken)) #131249

Closed

Description

@gbamqzkdyg

Description

From the version 10.0.0, BackgroundService.StartAsync schedules the worker via:

_executeTask = Task.Run(() => ExecuteAsync(_stoppingCts.Token), _stoppingCts.Token);

Passing _stoppingCts.Token as the second argument of Task.Run couples "should this delegate start at all" to the stopping token. If StopAsync (or Dispose) triggers _stoppingCts.Cancel() before the thread pool has begun executing the queued delegate, the delegate is never invoked — the task transitions directly to the Canceled state and the body of ExecuteAsync does not run.

Previous implementation started the work inline:

_executeTask = ExecuteAsync(_stoppingCts.Token);

This ran ExecuteAsync synchronously up to its first await on the caller's thread, guaranteeing the method body always began executing before any Cancel() could occur. The change to Task.Run(..., stoppingToken) introduced a start-time race that did not previously exist.

The change was introduced by the Commit Make BackgroundService run ExecuteAsync as task (#116283) · dotnet/runtime@72d1f3d.

Reproduction Steps

General Idea

  1. Implement a BackgroundService whose ExecuteAsync performs setup/teardown work that must run (e.g. graceful shutdown logic in a finally/catch after await Task.Delay(-1, stoppingToken)).

  2. Call StartAsync(CancellationToken.None) and, without yielding, await StopAsync(CancellationToken.None).

  3. Repeat in a loop (e.g. 1000 iterations).

Observed issue

Intermittently, ExecuteAsync's body never executes, so any work it was responsible for (including cleanup) is silently skipped. Because StopAsync awaits with ConfigureAwaitOptions.SuppressThrowing, the resulting cancellation is swallowed and no error surfaces.

Sample code for reproducing the issue

Paste the following code into Program.cs of a new Console App and run it twice with Microsoft.Extensions.Hosting >= version 10.0.0 installed.

using Repro;

for (var i = 0; i < 1000; ++i) await Operation.Run(i);
Console.WriteLine("Passed!");

namespace Repro
{
    using System;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Extensions.Hosting;

    public static class Operation
    {
        public static async Task Run(int i)
        {
            using var hostedService = new DerviedBackgroundService();
            Task startTask = hostedService.StartAsync(CancellationToken.None);
            await hostedService.StopAsync(CancellationToken.None).ConfigureAwait(false);

            if (!hostedService.ExecuteAsyncCancelled)
            {
                throw new Exception($"ExecuteAsync was not cancelled for iteration #{i}.");
            }
        }
    }

    public class DerviedBackgroundService : BackgroundService
    {

        private static readonly TimeSpan ShutdownTimeout = TimeSpan.FromSeconds(10);

        public bool ExecuteAsyncCancelled { get; private set; }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                await Task.Delay(-1, stoppingToken).ConfigureAwait(false);
            }
            catch (TaskCanceledException)
            {
            }

            using var cancellationTokenSource = new CancellationTokenSource(ShutdownTimeout);
            this.ExecuteAsyncCancelled = true;
        }
    }
}

Expected behavior

ExecuteAsync is always at least entered so its cancellation-handling / shutdown path runs, consistent with the prior inline behavior.

Actual behavior

We can see that the code runs into Exception when the version of Microsoft.Extensions.Hosting is >= 10.0.0, but it can always pass when the version of Microsoft.Extensions.Hosting is < 10.0.0, which means that ExecuteAsync is not granted to be entered before StartAsync being cancelled.

Image

Regression?

Yes.

Known Workarounds

No.

Configuration

This issue is unrelated to the .NET version.

Other information

Impact

• Silent skipping of ExecuteAsync: For short-lived services, or services stopped promptly after start (fast startup/shutdown cycles, health probes, failed host startup that triggers immediate shutdown, tests), the worker body may never run.

• Missed cleanup / shutdown logic: Any teardown, flush, drain, or graceful-shutdown code placed in ExecuteAsync (a common pattern) can be skipped, potentially leaving resources unreleased, data unflushed, or downstream systems un-notified.

• Failure is silent and non-deterministic: StopAsync suppresses the cancellation, so there is no exception or log. The behavior is timing-dependent, making it hard to reproduce and diagnose in production.

• Scope: Affects any consumer of the base BackgroundService following the documented Worker Service pattern; not limited to a single service.

Activity

  1. added
    untriaged
    on Jul 23, 2026
  2. dotnet-policy-service commented on Jul 23, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-threading-tasks
    See info in area-owners.md if you want to be subscribed.

  3. rjgotten commented on Jul 24, 2026

    @rjgotten

    This was an intentional documented breaking change.
    https://learn.microsoft.com/en-us/dotnet/core/compatibility/extensions/10.0/backgroundservice-executeasync-task

    If you need the old behavior back, you need to DIY it by implementing the IHostedService interface yourself.
    But if you do that, you might as well do it the right way around and create a AwaitingBackgroundService that holds the pipeline until explicitly released, so the work you have to complete before the pipeline is allowed to start serving requests, can itself also contain async components.

    (E.g. pass an Action ready delegate as a parameter to your base AwaitingBackgroundService class's ExecuteAsync which is tied to a TaskCompletionSource.)

  4. steveisok commented on Aug 12, 2026

    @steveisok
    Member

    This is distinct from the documented .NET 10 change. Moving ExecuteAsync entirely to the thread pool was intentional, but passing the stopping token to Task.Run also allows cancellation to prevent the delegate from being invoked at all.

    I was able to reproduce this: immediate StopAsync or Dispose resulted in a canceled execution task with zero calls to ExecuteAsync. Removing the scheduling token preserved background execution while invoking ExecuteAsync with an already-canceled stopping token.

  5. removed
    untriaged
    on Aug 12, 2026
  6. added this to the 11.0.0 milestone on Aug 12, 2026
  7. rjgotten commented on Aug 16, 2026

    @rjgotten

    @steveisok
    but passing the stopping token to Task.Run also allows cancellation to prevent the delegate from being invoked at all.

    Isn't that part and parcel of the Task.Run semantics to begin with?
    The whole point of moving the delegate entirely into Task.Run was that you don't get any guarantees on it running up to its first await until the pipeline has started. Which by transitivity also means you don't get a guarantee it has or will run at all if the pipeline immediately shuts down again.

    This sounds more like a documentation gap than an implementation gap.
    'Fixing' this is going to force CPU spend on a startup that will, after it has finished - if it finishes in time; and if it doesn't crash on e.g. ObjectDisposedException because host shutdowns are already running - still just lead to a shutdown.

    This is easy to miss, but a potential real scenario for containerized apps that use horizontal scaling and are subject to erratic scale-up/-down where they may decide on a scale-up only to moments later ask for a scale-down while background hosted services that are asynchronously reaching their ready-state, but are internally inside a longer-running synchronous block that is not cancelable immediately via cooperative cancellation, are still running and holding everything up. Because they cannot gracefully shut down until they reach their first opportunity to query the token's state.

  8. steveisok commented on Aug 18, 2026

    @steveisok
    Member

    @rjgotten there definitely is a trade-off and stopping quickly may mean doing some unnecessary startup work. The current implementation is timing dependent in that sometimes ExecuteAsync runs, sometimes not. The PR I created makes that deterministic.

    @jeffhandley who's the right person to weigh in on which approach we want?

  9. rjgotten commented on Aug 19, 2026

    @rjgotten

    @steveisok
    It's not just a matter of 'some unnecessary work'.
    Not passing the token and allowing the task to start unconditionally creates a dead zone dependent on how well the consumer's ExecuteAsync implementation handles the passed in cancellation token to avoid situations such as pulling services from a service provider that may already be disposing during host shutdown. It widens the possibility for ObjectDisposedException to occur.

  10. added a commit that references this issue on Aug 21, 2026
    1fb02ff
  11. locked and limited conversation to collaborators on Sep 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions