diff --git a/test/Libraries/Microsoft.Extensions.Diagnostics.ResourceMonitoring.Tests/ResourceMonitoringServiceTests.cs b/test/Libraries/Microsoft.Extensions.Diagnostics.ResourceMonitoring.Tests/ResourceMonitoringServiceTests.cs index fdfdf41da2d..6de754a2366 100644 --- a/test/Libraries/Microsoft.Extensions.Diagnostics.ResourceMonitoring.Tests/ResourceMonitoringServiceTests.cs +++ b/test/Libraries/Microsoft.Extensions.Diagnostics.ResourceMonitoring.Tests/ResourceMonitoringServiceTests.cs @@ -245,7 +245,7 @@ public async Task RunTrackerAsync_IfProviderThrows_LogsError() }), new List { - new GenericPublisher((_) => e.Set()) + new GenericPublisher((_) => ResilientSetEvent(e)) }, clock); @@ -322,7 +322,7 @@ public async Task ResourceUtilizationTracker_InitializedProperly_InvokesPublishe new GenericPublisher(_ => { publisherCalled = true; - autoResetEvent.Set(); + ResilientSetEvent(autoResetEvent); }) }, clock); @@ -415,10 +415,7 @@ public async Task ResourceUtilizationTracker_WhenInitializedWithZeroSnapshots_Re Create(options), new List { - new GenericPublisher(_ => - { - autoResetEvent.Set(); - }), + new GenericPublisher(_ => ResilientSetEvent(autoResetEvent)) }, clock); @@ -527,10 +524,7 @@ public async Task ResourceUtilizationTracker_WhenInitializedWithProperSnapshots_ Create(options), new List { - new GenericPublisher(_ => - { - autoResetEvent.Set(); - }), + new GenericPublisher(_ => ResilientSetEvent(autoResetEvent)) }, clock); @@ -711,4 +705,32 @@ public async Task Disposing_Service_Twice_Does_Not_Throw() var type = typ.GetField(name, BindingFlags.NonPublic | BindingFlags.Instance); return (T?)type?.GetValue(tracker); } + + private static void ResilientSetEvent(AutoResetEvent e) + { + try + { + e.Set(); + } +#pragma warning disable CA1031 + catch +#pragma warning restore CA1031 + { + // can happen since test termination is racy and the event might have already been disposed + } + } + + private static void ResilientSetEvent(ManualResetEventSlim e) + { + try + { + e.Set(); + } +#pragma warning disable CA1031 + catch +#pragma warning restore CA1031 + { + // can happen since test termination is racy and the event might have already been disposed + } + } }