Search code examples
c#.netdestructorcrash-dumpsapplication-state

How to ensure saving of application state on crash c#


I am very new to c# programming, so that in mind:

I have an in-memory data object with data I need to save the information when(if) my application were to crash OR closed. Is there a way to do this deterministically or reliably?

I have been looking at destructors

~MyObjectName(){}

finalizers and Dispose(),

but as far as I understand none of these will do reliably what I want?

Currently I am using the destructor, and it works when I am closing the program, but this doesn't mean it will work on crashing, or always.

Should I be looking at events as well?


Solution

  • There is no 100% reliable mechanism that you can use to save data (or do anything else for that matter) when a process (any process, not just a .Net process) terminates - most processes can be terminated at any point using the "End Process" option in the task manager, when this happens the process is immediately killed. As a more extreme example the power cord could be pulled out the back of the machine.

    If its not 100% necessary that this data object be up-to-date and saved once the process is killed then the AppDomain.UnhandledException Event may suffice.

    If its absolutely 100% necessary that this be the case then you need to be continuously saving this information as the process is running - there is absolutely no guarentee that you will get a chance to do it at a later date. This is how databases operate, no transaction returns until some record of the change has been recorded to disk in some format (e.g. a transaction log). This is what the D stands for in ACID.