Repository navigation
Description
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
-
Implement a
BackgroundServicewhoseExecuteAsyncperforms setup/teardown work that must run (e.g. graceful shutdown logic in a finally/catch afterawait Task.Delay(-1, stoppingToken)). -
Call
StartAsync(CancellationToken.None)and, without yielding,await StopAsync(CancellationToken.None). -
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.
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
dotnet-policy-service commentedon Jul 23, 2026
Tagging subscribers to this area: @dotnet/area-system-threading-tasks
See info in area-owners.md if you want to be subscribed.
rjgotten commentedon Jul 24, 2026
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
IHostedServiceinterface yourself.But if you do that, you might as well do it the right way around and create a
AwaitingBackgroundServicethat 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 readydelegate as a parameter to your baseAwaitingBackgroundServiceclass'sExecuteAsyncwhich is tied to aTaskCompletionSource.)steveisok commentedon Aug 12, 2026
This is distinct from the documented .NET 10 change. Moving
ExecuteAsyncentirely to the thread pool was intentional, but passing the stopping token toTask.Runalso allows cancellation to prevent the delegate from being invoked at all.I was able to reproduce this: immediate
StopAsyncorDisposeresulted in a canceled execution task with zero calls toExecuteAsync. Removing the scheduling token preserved background execution while invokingExecuteAsyncwith an already-canceled stopping token.rjgotten commentedon Aug 16, 2026
Isn't that part and parcel of the
Task.Runsemantics to begin with?The whole point of moving the delegate entirely into
Task.Runwas 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.
ObjectDisposedExceptionbecause 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.
steveisok commentedon Aug 18, 2026
@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
ExecuteAsyncruns, sometimes not. The PR I created makes that deterministic.@jeffhandley who's the right person to weigh in on which approach we want?
rjgotten commentedon Aug 19, 2026
@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.
Ensure BackgroundService invokes ExecuteAsync after start (dotnet#132241