closing stream writer creates error

T

tshad

I have a class that handles my csv file output from my web page.

I get an error when it tries to close the StreamWriter. Says it is already
closed but I never specifically closed it.

public class CsvWriter
{
private StringBuilder stringOut = null;
private StreamWriter csvWriter = null;

public CsvWriter(string fileName)
{
csvWriter = new StreamWriter(fileName);
}
~CsvWriter()
{
csvWriter.Close();
}
....

Why would that happen?

Thanks,

Tom
 
P

Peter Duniho

tshad said:
I have a class that handles my csv file output from my web page.

I get an error when it tries to close the StreamWriter. Says it is already
closed but I never specifically closed it.

public class CsvWriter
{
private StringBuilder stringOut = null;
private StreamWriter csvWriter = null;

public CsvWriter(string fileName)
{
csvWriter = new StreamWriter(fileName);
}
~CsvWriter()
{
csvWriter.Close();
}
....

Why would that happen?

You appear to be misusing the finalizer syntax.

The direct answer to your question is: the GC is closing your
StreamWriter, because it happens to get finalized before your own object.

The more correct answer is that your class, as shown here, should not
have a finalizer at all, and you should be explicitly closing the
StreamWriter in a deterministic way.

Pete
 
S

Scott M.

tshad said:
I have a class that handles my csv file output from my web page.

I get an error when it tries to close the StreamWriter. Says it is
already closed but I never specifically closed it.

public class CsvWriter
{
private StringBuilder stringOut = null;
private StreamWriter csvWriter = null;

public CsvWriter(string fileName)
{
csvWriter = new StreamWriter(fileName);
}
~CsvWriter()
{
csvWriter.Close();
}
...

Why would that happen?

Thanks,

Tom

Your attempt to close the streamwriter comes in the class's finalizer method
(the method that gets called by the .NET Framework just before the object is
collected from memory by the garbage collector).

..NET uses non-deterministic finalization for objects allocated onto the
memory heap. This means that objects are not removed from memory at the
point that your application's code is done using them and that you, the
programmer, do not determine the exact moment that your object is removed
from memory.

As such, the underlying streamwriter that your code is attempting to work
with (csvWriter) at the time of CsvWriter's finalization, may already have
been collected by the garbage collector.

You should create a dispose/finalize pattern, where the timing of the call
to the dispose method can be determined and the finalizer is just there in
case the user of your class were to forget to call dispose.

-Scott
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top