I have code like this:
~MyClass() {
try {
if (Database.Exists(_connectionString))
{
Database.Delete(_connectionString);
}
} catch { }
}
Database
is a static class of Entity Framework, whereas _connectionString
is a private readonly string
set by the ctor. The idea is that if someone forgot to Dispose the class, we still clean state (in my case, this is part of an integration test where the test runner doesn't call Dispose if there's an unhandled exception in the test, so it's not something I can fix on my side)
However, Finalizers are generally not supposed to call class members because they might be disposed already, so if I end up in a scenario where the _connectionString
is already collected, I might have a problem.
Is there a way to do this safely (e.g,, using some sort of GC.KeepAlive
construct?)