D
David L.S.
After read about GC and Finalize, I try this test:
public void Test()
{
int num1;
FileStream stream1;
StreamWriter writer1;
for (num1 = 0; (num1 < 100); num1 += 1)
{
stream1 = new
FileStream(@"c:\temp\GC_Test\TestLOG.txt", FileMode.Append);
writer1 = new StreamWriter(stream1);
writer1.WriteLine("Now!!!");
writer1.Flush();
//writer1.Close();
stream1 = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
This is what I'm trying to do:
Open a file and put the reference in stream1 variable.
After this, kill reference and ask for GC to collect objects and execute the
FileStream.Finalize method using WaitForPendingFinalizers method. The
FileStream.Finalize must free the file's handle without executing
FileStream.Close.
But, for my surprise, on second iteration, I get this exception:
An unhandled exception of type 'System.IO.IOException' occurred in
mscorlib.dll
Additional information: The process cannot access the file
"c:\temp\GC_Test\TestLOG.txt" because it is being used by another process.
What I'm doing wrong?
Is GC executing FileStream.Finalize method?
Is GC methods synchronous?
public void Test()
{
int num1;
FileStream stream1;
StreamWriter writer1;
for (num1 = 0; (num1 < 100); num1 += 1)
{
stream1 = new
FileStream(@"c:\temp\GC_Test\TestLOG.txt", FileMode.Append);
writer1 = new StreamWriter(stream1);
writer1.WriteLine("Now!!!");
writer1.Flush();
//writer1.Close();
stream1 = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
This is what I'm trying to do:
Open a file and put the reference in stream1 variable.
After this, kill reference and ask for GC to collect objects and execute the
FileStream.Finalize method using WaitForPendingFinalizers method. The
FileStream.Finalize must free the file's handle without executing
FileStream.Close.
But, for my surprise, on second iteration, I get this exception:
An unhandled exception of type 'System.IO.IOException' occurred in
mscorlib.dll
Additional information: The process cannot access the file
"c:\temp\GC_Test\TestLOG.txt" because it is being used by another process.
What I'm doing wrong?
Is GC executing FileStream.Finalize method?
Is GC methods synchronous?