I have a piece of code like this:
Class Program
{
static StreamReader sr = null;
static int var=0;
static Program()
{
sr = new StreamReader("input.txt")
}
~Program()
{
sr.Dispose();
}
static void main(string args[])
{
//do something with input here
}
}
This may not be a good practice, but I just want to use this example to ask how the deconstructor and GC works.
My question is: Will ~Program() get called at a non-determined time or it won’t be called at all in this case. If the deconstructor won’t get called, then how GC collect the unmanaged resources and managed resources.
It probably wouldn’t reclaim those resources until the AppDomain or process is unloaded.
If you never instantiate an object, it will never be destroyed. This is exactly why you want, probably something like a Singleton. I believe there is a flavor called “Phoenix Singleton,” that will allow a Singleton to be cleaned up and then rebuilt when it is needed again. You could implement it using a
WeakReferenceto the singleton object.In any case, for a simple program that runs for a bounded period of time, I wouldn’t worry about it unless it becomes a problem… the resources will be cleaned up when the process exits.