Skip to content

Commit

Permalink
Merge pull request #1353 from botinko/concurrentBagLeak
Browse files Browse the repository at this point in the history
Fix memory leak regression
  • Loading branch information
alistairjevans authored Oct 25, 2022
2 parents 0362f7e + 885ed44 commit 58e297d
Showing 1 changed file with 18 additions and 11 deletions.
29 changes: 18 additions & 11 deletions src/Autofac/Core/Registration/DefaultRegisteredServicesTracker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -249,17 +249,7 @@ protected override void Dispose(bool disposing)
registration.Dispose();
}

// If we do not explicitly empty the ConcurrentBag that stores our registrations,
// this will cause a memory leak due to threads holding a reference to the bag.
// In netstandard2.0 the faster 'Clear' method is not available,
// so we have do this manually. We'll use the faster method if it's available though.
#if NETSTANDARD2_0
while (_registrations.TryTake(out _))
{
}
#else
_registrations.Clear();
#endif
ClearRegistrations();

base.Dispose(disposing);
}
Expand All @@ -272,9 +262,26 @@ protected override async ValueTask DisposeAsync(bool disposing)
await registration.DisposeAsync().ConfigureAwait(false);
}

ClearRegistrations();

// Do not call the base, otherwise the standard Dispose will fire.
}

private void ClearRegistrations()
{
// If we do not explicitly empty the ConcurrentBag that stores our registrations,
// this will cause a memory leak due to threads holding a reference to the bag.
// In netstandard2.0 the faster 'Clear' method is not available,
// so we have do this manually. We'll use the faster method if it's available though.
#if NETSTANDARD2_0
while (_registrations.TryTake(out _))
{
}
#else
_registrations.Clear();
#endif
}

private ServiceRegistrationInfo GetInitializedServiceInfo(Service service)
{
var createdEphemeralSet = false;
Expand Down

0 comments on commit 58e297d

Please sign in to comment.