Skip to content

Don't dispose timers if we're in our UnhandledException handler. #103937

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public class MemoryCache : ObjectCache, IEnumerable, IDisposable
private bool _throwOnDisposed;
private EventHandler _onAppDomainUnload;
private UnhandledExceptionEventHandler _onUnhandledException;
private int _inUnhandledExceptionHandler;
#if NET
[UnsupportedOSPlatformGuard("browser")]
private static bool _countersSupported => !OperatingSystem.IsBrowser();
Expand Down Expand Up @@ -238,8 +239,11 @@ private void OnAppDomainUnload(object unusedObject, EventArgs unusedEventArgs)
Dispose();
}

internal bool InUnhandledExceptionHandler => _inUnhandledExceptionHandler == 1;
private void OnUnhandledException(object sender, UnhandledExceptionEventArgs eventArgs)
{
Interlocked.Exchange(ref _inUnhandledExceptionHandler, 1);

// if the CLR is terminating, dispose the cache.
// This will dispose the perf counters
if (eventArgs.IsTerminating)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -340,8 +340,14 @@ public void Dispose()
GCHandleRef<Timer> timerHandleRef = _timerHandleRef;
if (timerHandleRef != null && Interlocked.CompareExchange(ref _timerHandleRef, null, timerHandleRef) == timerHandleRef)
{
timerHandleRef.Dispose();
Dbg.Trace("MemoryCacheStats", "Stopped CacheMemoryTimers");
// #64115 and #102666 - It's not safe to dispose timers in our unhandled exception handler. But if we're in the unhandled
// exception handler, then the process is going away. We don't really need to clean up timers. (Interactions of
// processes/AppDomains/Timers/PerfCounters/etc were different in NetFx from which this package is derived.)
if (!_memoryCache.InUnhandledExceptionHandler)
{
timerHandleRef.Dispose();
Dbg.Trace("MemoryCacheStats", "Stopped CacheMemoryTimers");
}
}
}
while (_inCacheManagerThread != 0)
Expand Down
Loading