ServiceEndpointWatcher logs normal cancellation as an error

Abierto Apto para principiantes
#7,940 1 comentario 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

@seragAhmed ya está trabajando en esto.

Desde el 12/11/2026.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
76/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
csharp

Línea de trabajo

Empieza por src/Libraries/Microsoft.Extensions.ServiceDiscovery/ServiceEndpointWatcher.cs, especialmente DisposeAsync y RefreshAsyncInternal, que el issue identifica como la ruta de cancelación y registro. Comprueba si las pruebas existentes de ServiceEndpointWatcher cubren la eliminación durante una actualización en segundo plano. Se considerará terminado cuando esta cancelación normal ya no registre un error de resolución y haya una prueba que cubra la reproducción.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

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.

Lenguaje dominante
C#
Estrellas
3.3k
Forks
919
Merge medio
2 d 2 h
PR fusionados (30 d)
35

Preparar el entorno

Abrir en Codespaces

Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de dotnet/extensions

Todos los issues de dotnet/extensions

Issues similares

Más issues de C#

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.