views:

98

answers:

2

I'd like to save data from a console application in its final state when closed. I've figured out how to use serialization to save the data, but not how to make this happen when the application closes.

One method is to set an unmanaged handler to intercept the close command and perform an operation, however once the event handler has been called, GC() has already been run and the managed program is no longer in memory.

Any ideas?


Edit: The essential problem here is that I have an object that listens to a stream for the life of the program. If the program is then closed externally (eg by pushing the x in the corner) then no other code in the Main() method is executed, bypassing the closing serialization code.

+4  A: 

Normally, you'd just put this code at the end of your Main routine - this would then be the last thing that is run prior to your console application closing.

If you're trying to handle something at the last possible moment before the managed code shuts down, you can subscribe to AppDomain.DomainUnload. This event is fired right as the AppDomain is unloaded.

Reed Copsey
+1  A: 

I would create an application-life-time class instance that stores the state, and add serialization code to its destructor.

Another idea is using try{} finally{} in your program.

ironic