Skip to content
This repository was archived by the owner on Jun 10, 2020. It is now read-only.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ namespace Microsoft.ApplicationInsights.AspNetCore
{
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Diagnostics;
using Extensions;
using Microsoft.ApplicationInsights.AspNetCore.DiagnosticListeners;
Expand All @@ -13,8 +14,9 @@ namespace Microsoft.ApplicationInsights.AspNetCore
/// </summary>
internal class ApplicationInsightsInitializer : IObserver<DiagnosticListener>, IDisposable
{
private readonly List<IDisposable> subscriptions;
private readonly ConcurrentBag<IDisposable> subscriptions;
private readonly IEnumerable<IApplicationInsightDiagnosticListener> diagnosticListeners;
private volatile bool shuttingDown = false;

/// <summary>
/// Initializes a new instance of the <see cref="ApplicationInsightsInitializer"/> class.
Expand All @@ -26,7 +28,7 @@ public ApplicationInsightsInitializer(
IServiceProvider serviceProvider)
{
this.diagnosticListeners = diagnosticListeners;
this.subscriptions = new List<IDisposable>();
this.subscriptions = new ConcurrentBag<IDisposable>();

// Add default logger factory for debug mode only if enabled and instrumentation key not set
if (options.Value.EnableDebugLogger && string.IsNullOrEmpty(options.Value.InstrumentationKey))
Expand All @@ -48,6 +50,11 @@ public void Start()
/// <inheritdoc />
void IObserver<DiagnosticListener>.OnNext(DiagnosticListener value)
{
if (shuttingDown)
{
return;
}

foreach (var applicationInsightDiagnosticListener in this.diagnosticListeners)
{
if (applicationInsightDiagnosticListener.ListenerName == value.Name)
Expand Down Expand Up @@ -75,13 +82,16 @@ public void Dispose()

protected virtual void Dispose(bool disposing)
{
if (disposing)
if (!disposing)
{
foreach (var subscription in this.subscriptions)
{
subscription.Dispose();
}
return;
}

shuttingDown = true;
foreach (var subscription in this.subscriptions)
{
subscription.Dispose();
}
}
}
}
}