ServiceEndpointWatcher logs normal cancellation as an error

Open Beginner friendly
#7,940 1 comment 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

@seragAhmed is already working on this.

Since Nov 12, 2026.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
76/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
csharp

Research direction

Start with src/Libraries/Microsoft.Extensions.ServiceDiscovery/ServiceEndpointWatcher.cs, especially DisposeAsync and RefreshAsyncInternal, which the issue identifies as the cancellation and logging path. Check the existing ServiceEndpointWatcher tests for coverage of disposal during a background refresh. Done means this normal cancellation no longer logs a resolution error, with a test covering the repro.

Written by the indexing model from the issue text.

Description

bug untriaged
Description

Hi!

I'm getting Error resolving endpoints for service ... when a watcher is disposed during a background refresh. The refresh is cancelled by the watcher itself, but that cancellation ends up in the error log.

I ran into this with DNS discovery. The first lookup worked, then a background refresh was left waiting for a DNS response. About 20 seconds after the lookup, idle-watcher cleanup cancelled it and logged TaskCanceledException. The next lookup worked too.

Reproduction Steps

Here is a smaller repro with a custom provider, so there is no DNS server to set up.

Create a .NET 10 console app and add Microsoft.Extensions.ServiceDiscovery 10.11.0 and a framework reference to Microsoft.AspNetCore.App. Replace Program.cs with:

using System.Diagnostics.CodeAnalysis;
using System.Net;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.ServiceDiscovery;

var factory = new SlowRefreshProvider();
var services = new ServiceCollection();
services.AddLogging(logging => logging.AddSimpleConsole());
services.AddServiceDiscoveryCore(options => options.RefreshPeriod = TimeSpan.FromMilliseconds(100));
services.AddSingleton<IServiceEndpointProviderFactory>(factory);

await using var provider = services.BuildServiceProvider();
var resolver = provider.GetRequiredService<ServiceEndpointResolver>();
await resolver.GetEndpointsAsync("http://sample", CancellationToken.None);
await factory.RefreshStarted.Task.WaitAsync(TimeSpan.FromSeconds(5));
Console.WriteLine("Disposing the resolver during a background refresh");
await resolver.DisposeAsync();
Console.WriteLine("Disposed successfully");

sealed class SlowRefreshProvider : IServiceEndpointProviderFactory, IServiceEndpointProvider
{
    private int calls;
    public TaskCompletionSource RefreshStarted { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);

    public bool TryCreateProvider(ServiceEndpointQuery query, [NotNullWhen(true)] out IServiceEndpointProvider? provider)
    {
        provider = this;
        return true;
    }

    public async ValueTask PopulateAsync(IServiceEndpointBuilder endpoints, CancellationToken cancellationToken)
    {
        if (Interlocked.Increment(ref calls) == 1)
        {
            endpoints.Endpoints.Add(ServiceEndpoint.Create(new DnsEndPoint("localhost", 8080)));
            return;
        }

        RefreshStarted.SetResult();
        await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken);
    }

    public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}

Run with dotnet run. The first lookup succeeds. Once the background refresh starts, the example disposes the resolver. The provider uses the supplied cancellation token and doesn't throw anything on its own.

Expected behavior

I'd expect cancellation during disposal to be handled without logging a resolution error.

Actual behavior
Disposing the resolver during a background refresh
fail: Microsoft.Extensions.ServiceDiscovery.ServiceEndpointWatcher[4]
      Error resolving endpoints for service 'http://sample'.
      System.Threading.Tasks.TaskCanceledException: A task was canceled.
         at SlowRefreshProvider.PopulateAsync(...)
         at Microsoft.Extensions.ServiceDiscovery.ServiceEndpointWatcher.RefreshAsyncInternal()
Disposed successfully
Regression?

No response

Known Workarounds

No response

Configuration

Tested with package 10.11.0, .NET SDK 10.0.403, macOS arm64.

Other information

From the watcher source for 10.11.0, this seems to happen because DisposeAsync cancels _disposalCancellation, and RefreshAsyncInternal logs the resulting exception as ResolutionFailed. Disposal suppresses the exception afterwards, but the error has already been logged.

The same catch/log path is still in main. I haven't tested an 11.x package.

Dominant language
C#
Stars
3.3k
Forks
919
Avg merge
2d 2h
Merged PRs (30d)
35

Getting set up

Open in Codespaces

Starts the project's dev container in your browser, under your own GitHub account.

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 dotnet/extensions

All issues in dotnet/extensions

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.