How can we solve an unhandled exception thrown by a finalizer, which clearly does not come from our code?
By event AppDomain.CurrentDomain.UnhandledException
we once in a while log an Exception, which does not come from our code and is terminating the program. The stacktrace starts with the Finalize()
method and is called on a class A
, which we do not use anywhere.
Questions
- Can we somehow detect a library/NuGet/project, which is causing this?
- Can we maybe do some hard core hack like:
- Changing GC behaviour (catching exceptions on finalizer, printing the faulted object ...)
- Continously finding all instances of
A
in memory and either recognizing its origin (what created them or has reference on them) or calling their finalizer ourselves at the right moment in try catch?
- Something else?
THE SPECIFIC INFO:
The full stacktrace starts with frames System.ComponentModel.Component.Finalize()
and System.IO.FileSystemWatcher.Dispose(Boolean disposing)
. The FileSystemWatcher
is derived from the Component
class - therefore the finalizer is called on the FileSystemWatcher
.
We do not use class FileSystemWatcher
anywhere in our code. It may come from some NuGet, but we use many of them. Our solution is wide, we have no clue, what could it cause. We use .Net Core 2.2 running in dockers on Linux.
The logged exception info:
AggregateException: One or more errors occurred. (Object reference not set to an instance of an object.);
InnerException: NullReferenceException: Object reference not set to an instance of an object.
Stacktrace:
at System.Threading.CancellationTokenSource.CallbackNode.<>c.<ExecuteCallback>b__10_0(Object s)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException)
--- End of inner exception stack trace ---
at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException)
at System.IO.FileSystemWatcher.StopRaisingEvents()
at System.IO.FileSystemWatcher.Dispose(Boolean disposing)
at System.ComponentModel.Component.Finalize()