runtime: Endless HttpMessageHandler cleanup cycle with C# cmdlets using .NET generic host

area-Extensions-HttpClientFactory

Hi there,

I have a c# PowerShell module with cmdlets that make use of the .NET generic host. It uses .NET standard 2.1.

Unfortunately after a few calls to the cmdlets I start to get endless debug messages in the PowerShell terminal…

dbug: Microsoft.Extensions.Http.DefaultHttpClientFactory[100]
      Starting HttpMessageHandler cleanup cycle with 1 items

I looked at this thread (https://github.com/aspnet/HttpClientFactory/issues/165) and used JetBrains’ dotMemory to force a garbage collection but it doesn’t fix it.

I did the shortest path analysis below but to be honest I’m not sure entirely how to interpret it.

Any help appreciated…

Annotation 2020-05-09 230724

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 2
  • Comments: 31 (11 by maintainers)

Most upvoted comments

This works as expected.

The cleanup can only process the handlers that were garbage collected. Until your app triggers a GC, the clean up is not able to verify that the handlers are not used anymore.

For the illustration purposes, here is an example of manually triggering Full GC (full src in the end of the post):

services.AddKeyedTransient<DisposeTrackingHandler>(KeyedService.AnyKey);
services.ConfigureHttpClientDefaults(b => b.SetHandlerLifetime(TimeSpan.FromSeconds(5)));

services.AddHttpClient("discard")
    .AddHttpMessageHandler(sp => sp.GetRequiredKeyedService<DisposeTrackingHandler>("discard"));

// ...

_ = httpClientFactory.CreateClient("discard");

PrintAliveHandlers();
await Delay30s();

GcCollect();
await Delay30s();

PrintAliveHandlers();

// -----

void GcCollect()
{
    log.LogInformation("GcCollect");
    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();
}

Which shows that after GC the handler gets successfully processed and disposed:

info: Program[0]
      Creating 'discard'
trce: DisposeTrackingHandler[0]
      _name='discard', .ctor
info: Program[0]
      Alive handlers: [ discard ]
trce: Program[0]
      Delay30s
dbug: Microsoft.Extensions.Http.DefaultHttpClientFactory[103]
      HttpMessageHandler expired after 5000ms for client 'discard'
dbug: Microsoft.Extensions.Http.DefaultHttpClientFactory[100]
      Starting HttpMessageHandler cleanup cycle with 1 items
dbug: Microsoft.Extensions.Http.DefaultHttpClientFactory[101]
      Ending HttpMessageHandler cleanup cycle after 0.1875ms - processed: 0 items - remaining: 1 items
dbug: Microsoft.Extensions.Http.DefaultHttpClientFactory[100]
      Starting HttpMessageHandler cleanup cycle with 1 items
dbug: Microsoft.Extensions.Http.DefaultHttpClientFactory[101]
      Ending HttpMessageHandler cleanup cycle after 0.0016ms - processed: 0 items - remaining: 1 items
info: Program[0]
      GcCollect
trce: Program[0]
      Delay30s
dbug: Microsoft.Extensions.Http.DefaultHttpClientFactory[100]
      Starting HttpMessageHandler cleanup cycle with 1 items
trce: DisposeTrackingHandler[0]
      _name='discard', Dispose
dbug: Microsoft.Extensions.Http.DefaultHttpClientFactory[101]
      Ending HttpMessageHandler cleanup cycle after 0.7665ms - processed: 1 items - remaining: 0 items
info: Program[0]
      Alive handlers: [  ]

If GC doesn’t help, it is possible a handler is erroneously rooted (saved in a field or in a variable) for the prolonged period of time, so it can’t be collected in time.

services.AddHttpClient("rooted")
    .AddHttpMessageHandler(sp => sp.GetRequiredKeyedService<DisposeTrackingHandler>("rooted"));

services.AddHttpClient("weak-ref")
    .AddHttpMessageHandler(sp => sp.GetRequiredKeyedService<DisposeTrackingHandler>("weak-ref"));

// ...

log.LogInformation($"Creating 'rooted'");
var rootedClient = httpClientFactory.CreateClient("rooted");

log.LogInformation($"Creating 'weak-ref'");
var weakRefClient = httpClientFactory.CreateClient("weak-ref");
var weakRef = new WeakReference(weakRefClient);
weakRefClient = null;

PrintAliveHandlers();
await Delay30s();

GcCollect();
await Delay30s();

PrintAliveHandlers();

log.LogInformation("Unrooting 'rooted'");
rootedClient.Dispose();
rootedClient = null;

GcCollect();
await Delay30s();

PrintAliveHandlers();

You can see that weak-ref got cleaned up right away, while rooted had to wait until it was not rooted anymore

info: Program[0]
      Creating 'rooted'
trce: DisposeTrackingHandler[0]
      _name='rooted', .ctor
info: Program[0]
      Creating 'weak-ref'
trce: DisposeTrackingHandler[0]
      _name='weak-ref', .ctor
info: Program[0]
      Alive handlers: [ rooted, weak-ref ]
trce: Program[0]
      Delay30s
dbug: Microsoft.Extensions.Http.DefaultHttpClientFactory[103]
      HttpMessageHandler expired after 5000ms for client 'rooted'
dbug: Microsoft.Extensions.Http.DefaultHttpClientFactory[103]
      HttpMessageHandler expired after 5000ms for client 'weak-ref'
dbug: Microsoft.Extensions.Http.DefaultHttpClientFactory[100]
      Starting HttpMessageHandler cleanup cycle with 2 items
dbug: Microsoft.Extensions.Http.DefaultHttpClientFactory[101]
      Ending HttpMessageHandler cleanup cycle after 0.1766ms - processed: 0 items - remaining: 2 items
dbug: Microsoft.Extensions.Http.DefaultHttpClientFactory[100]
      Starting HttpMessageHandler cleanup cycle with 2 items
dbug: Microsoft.Extensions.Http.DefaultHttpClientFactory[101]
      Ending HttpMessageHandler cleanup cycle after 0.0022ms - processed: 0 items - remaining: 2 items
info: Program[0]
      GcCollect
trce: Program[0]
      Delay30s
dbug: Microsoft.Extensions.Http.DefaultHttpClientFactory[100]
      Starting HttpMessageHandler cleanup cycle with 2 items
trce: DisposeTrackingHandler[0]
      _name='weak-ref', Dispose
dbug: Microsoft.Extensions.Http.DefaultHttpClientFactory[101]
      Ending HttpMessageHandler cleanup cycle after 0.9956ms - processed: 1 items - remaining: 1 items
dbug: Microsoft.Extensions.Http.DefaultHttpClientFactory[100]
      Starting HttpMessageHandler cleanup cycle with 1 items
dbug: Microsoft.Extensions.Http.DefaultHttpClientFactory[101]
      Ending HttpMessageHandler cleanup cycle after 0.0017ms - processed: 0 items - remaining: 1 items
dbug: Microsoft.Extensions.Http.DefaultHttpClientFactory[100]
      Starting HttpMessageHandler cleanup cycle with 1 items
dbug: Microsoft.Extensions.Http.DefaultHttpClientFactory[101]
      Ending HttpMessageHandler cleanup cycle after 0.0026ms - processed: 0 items - remaining: 1 items
info: Program[0]
      Alive handlers: [ rooted ]
info: Program[0]
      Unrooting 'rooted'
info: Program[0]
      GcCollect
trce: Program[0]
      Delay30s
dbug: Microsoft.Extensions.Http.DefaultHttpClientFactory[100]
      Starting HttpMessageHandler cleanup cycle with 1 items
trce: DisposeTrackingHandler[0]
      _name='rooted', Dispose
dbug: Microsoft.Extensions.Http.DefaultHttpClientFactory[101]
      Ending HttpMessageHandler cleanup cycle after 0.05ms - processed: 1 items - remaining: 0 items
info: Program[0]
      Alive handlers: [  ]

Complete runnable example
using System.Runtime.CompilerServices;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

var services = new ServiceCollection();

services.AddLogging(b => b
    .ClearProviders()
    .AddConsole()
    .SetMinimumLevel(LogLevel.Trace));

services.AddKeyedTransient<DisposeTrackingHandler>(KeyedService.AnyKey);

services.ConfigureHttpClientDefaults(b => b.SetHandlerLifetime(TimeSpan.FromSeconds(5)));

services.AddHttpClient("rooted")
    .AddHttpMessageHandler(sp => sp.GetRequiredKeyedService<DisposeTrackingHandler>("rooted"));

services.AddHttpClient("weak-ref")
    .AddHttpMessageHandler(sp => sp.GetRequiredKeyedService<DisposeTrackingHandler>("weak-ref"));

services.AddHttpClient("discard")
    .AddHttpMessageHandler(sp => sp.GetRequiredKeyedService<DisposeTrackingHandler>("discard"));

var serviceProvider = services.BuildServiceProvider();

// ---

var log = serviceProvider.GetRequiredService<ILogger<Program>>();
var httpClientFactory = serviceProvider.GetRequiredService<IHttpClientFactory>();

log.LogInformation($"Creating 'rooted'");
var rootedClient = httpClientFactory.CreateClient("rooted");

log.LogInformation($"Creating 'weak-ref'");
var weakRefClient = httpClientFactory.CreateClient("weak-ref");
var weakRef = new WeakReference(weakRefClient);
weakRefClient = null;

log.LogInformation($"Creating 'discard'");
_ = httpClientFactory.CreateClient("discard");

// ---

PrintAliveHandlers();
await Delay30s();

GcCollect();
await Delay30s();

PrintAliveHandlers();

log.LogInformation("Unrooting 'rooted'");
rootedClient.Dispose();
rootedClient = null;

GcCollect();
await Delay30s();

PrintAliveHandlers();

// ----------------------------------------------------------------

void GcCollect()
{
    log.LogInformation("GcCollect");
    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();
}

async Task Delay30s()
{
    log.LogTrace("Delay30s");
    await Task.Delay(TimeSpan.FromSeconds(30));
}

void PrintAliveHandlers()
{
    log.LogInformation("Alive handlers: [ {list} ]", DisposeTrackingHandler.GetNames());
}

// ----------------------------------------------------------------

class DisposeTrackingHandler : DelegatingHandler
{
    private static readonly List<string> _instanceNames = [];
    public static string GetNames()
    {
        lock (_instanceNames)
        {
            return string.Join(", ", _instanceNames);
        }
    }

    private readonly ILogger<DisposeTrackingHandler> _log;
    private readonly string _name;

    private bool _disposed;

    public DisposeTrackingHandler([ServiceKey] string name, ILogger<DisposeTrackingHandler> log)
    {
        _log = log;
        _name = name;

        Trace();
        lock (_instanceNames)
        {
            _instanceNames.Add(_name);
        }
    }

    protected override void Dispose(bool disposing)
    {
        if (_disposed)
        {
            return;
        }
        _disposed = true;

        Trace();
        base.Dispose(disposing);
        lock (_instanceNames)
        {
            _instanceNames.Remove(_name);
        }
    }

    private void Trace([CallerMemberName] string? memberName = null) => _log.LogTrace("_name='{name}', {memberName}", _name, memberName ?? "(?)");
}

Still no solution on this? All my services are transient but everytime HttpMessageHandler gets expired after 2 minutes - it justs stacks items for cleanup cycle and nothing is processed but sometimes after stacking some more items its just randomly processes some of (but not all) remaining items and overall unprocessed items keeps increasing

And after long time of spamming in logs about cleanups it just sometimes cleanup them all. Is it intentional behaviour and I just have to supress these logs?

I believe the logging is by-design. It looks to me like your Service is keeping a reference to the HttpClient and that will keep the handler rooted. The service is registered as a singleton which I think means the service will be created once and kept alive for the lifetime of the host and the host will be kept alive by the cmdlet instance. The logging is just because you’ve enabled debug level logging and this debug statement is telling you the handler is still rooted by something after time has passed.

/cc @davidfowl @maryamariyan to check my understanding here. FYI @dotnet/ncl