I have a scenario where on application crash, I have to clear certain registry keys. I am trying to use Dispose() pattern for it. in case of application crash during garbage collection does the Dispose gets called to clear the registry???
Is there any other pattern to do such activities? I can not use Unhandled application handler as the code I want to call is not referenced directly by the Main application. I could use reflection but not sure if that's the right pattern.
any advise or experience in this matter will be really appreciated.
It sounds like you want to add an event handler to the AppDomain.UnhandledException
event, do some processing (writing to the registry in this case) and then let the program die.
Assuming that you're not doing anything odd like loading your library into a different AppDomain
you should be able to hook this from your library in a variety of ways. I've used a static constructor for this in the past and to hook the AssemblyResolve
event from a library.
Something like this:
public static class CrashHandler
{
public static bool Initialized { get; private set; }
[SecurityPermission(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlAppDomain)]
static CrashHandler()
{
AppDomain.CurrentDomain.UnhandleException += crash_handler;
Initialized = true;
}
static void crash_handler(object sender, UnhandledExceptionEventArgs args)
{
// do your thing here
}
}
In order to get this to actually fire you need to read the Initialized
value somewhere at least once. Add it to the constructor of one of your library objects that you can be sure will be instantiated early.