Reputation: 1389
Looking at 'System.IO.File.AppendAllText' code from the GAC it calls another method called 'InternalAppendAllText' which creates a new StreamWriter and writes the content to the file.
//mscorlib, System.IO
private static void InternalAppendAllText(string path, string contents, Encoding encoding)
{
using (StreamWriter writer = new StreamWriter(path, true, encoding))
{
writer.Write(contents);
}
}
My question is if I did a for loop calling System.IO.AppentAllText 5 times for example will the StreamWriter be created 5 times, each iteration it is initialized and disposed or it is only initialized once?
Example:
for(int i = 1; i < 4; ++i)
{
System.IO.File.AppendAllText("a", "a");
}
Upvotes: 2
Views: 250
Reputation: 14700
The using
block is expanded to the equivalent of this code:
StreamWriter writer;
try
{
writer = new StreamWriter(path, true, encoding))
writer.Write(contents);
}
finally
{
if (writer != null)
writer.Dispose();
}
So yes, whenever a using
block exits, the objects are disposed. Whenever you reenter the function, a new StreamWriter
will be initialized.
Note, however, that this doesn't have anything to do with the Garbage Collector. The GC will run when it feels like it, scan the allocated objects, notice that there are five StreamWriter
objects that aren't attached to any GC Root, and discard them. This is true whether or not you called Dispose
or used using
, it's just how the GC works.
What using
does here is release the unmanaged resource that the object holds - in this case, the file handle. If the StreamWriter
was not destroyed or otherwise explicitly closed, the file would have remained locked for editing until your process has finished or the GC decided to activate. This is what using
blocks and the IDisposable
interace are for - to make sure you explicitly release the objects that the GC doesn't know about.
Upvotes: 6
Reputation: 929
If you look at the decompiled code the Stream is in a using statement so it will be cleaned up. It will be initialized all 5 times but it will be cleaned up as soon as the code leaves the using statement.
Upvotes: 3