Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

correct way to store information to file when application shutdown

Tags:

c#

One of my class collects statistics during application execution and I want to store this statistics to disk when application finished. I never destroy this class inside my program so I have tried to store logs to file like that:

    ~Strategy()
    {
        foreach(var item in statisticItems)
        {
            log.WriteLine(item.Text);    // log is AutoFlush
        }
    }

However I do not see logs I expect to see and also I can not "catch" in debugger moment when destructor called.

Questions:

  • Why In debugger I can not catch moment when destructor is called? Isn't destructor must be called for every object when program finishes?
  • What should I use to log my stuff?
like image 625
Oleg Vazhnev Avatar asked Jul 17 '12 19:07

Oleg Vazhnev


People also ask

How is application data stored?

The ways for storing such data are as follows:Databases. Structured storages. Archives (as a specific form of structured storage) Remote (distributed, cloud) storages.

How do you preserve app data?

Use the directories within internal storage to save sensitive information that other apps shouldn't access. Shared storage: Store files that your app intends to share with other apps, including media, documents, and other files. Preferences: Store private, primitive data in key-value pairs.


1 Answers

The destructor (or finalizer) is not the place to put code like that. It is designed for releasing unmanaged resources. Destructors are called non-deterministically, so you can't rely on any of your objects being valid inside the destructor. And you can't catch it in the debugger because it is called on a separate thread, under very special circumstances. In short, do not use destructors, unless you know you need to.

The ideal way to log application shutdown is to simply place the logging code at the end of the Main method. You should make sure that you catch and log any exceptions that are thrown, and if that is the case, you can log the shutdown at the end of Main.

There will be a few edge cases where you won't be able to log the shutdown, because of errors such as a stack overflow. In those cases, you will need to rely on logs of what happened before the error.

like image 151
Kendall Frey Avatar answered Oct 26 '22 02:10

Kendall Frey