I created a function to make sure an object is disposed of properly. This function includes setting the object to null. I am wondering if the line that sets the object to null is useless (and hence I will remove the line), and then add a line to set the object to null in the calling function. My example is for the FileStream object, but I any other object (I think) can take its place. I know I can trace the execution of the program and see what is happening, however, I would like to know more information on the inner mechanisms (garbage collection?), does this work for any object, etc.
//Called function:
public static void DiscardFile(System.IO.FileStream file)
{
file.Flush();
file.Close();
file.Dispose();
//Does this work?
//When the function returns, is the file object really set to null?
file = null;
}
//Calling function:
public static void WriteStringToFile(string s, string fileName)
{
System.IO.StreamWriter file = new System.IO.StreamWriter(fileName);
file.Write(s);
DiscardFile(file);
//Is this redundant?
//Or is the line in the called function the redundant line?
file = null;
}
Thanks!
I have a loop that writes a thousand strings to files within 30 seconds. (The program will be writing 400K+ strings when it completes its execution.) I see that the loop waits (every so often) at the file.Write(s) line, and that the memory footprint of the app increases. That is for another thread, but wanted to know the behavior of the above code.
Thanks!