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:
The ways for storing such data are as follows:Databases. Structured storages. Archives (as a specific form of structured storage) Remote (distributed, cloud) storages.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With