Scope of StreamWriter in Static Class; resource usage implications

M

Merk

In a 2.0 Windows Forms app... in a static class I have a method named
WriteToLocalLog() that writes to a text file on the local machine.

I declare a StreamWriter at the class level (not inside the method), as
follows:
private static System.IO.StreamWriter streamWriter_ToLocalLog;

The reason I declare streamWriter_ToLocalLog at the class level and not
inside the WriteToLocalLog() method is so I can reuse the StreamWriter
between calls to WriteToLocalLog().

My question:
Is there an obvious problem or risk with doing it this way? I'm wondering if
I would need to specifically .Close() it... else risk a memory leak or
otherwise tie up system resources once the app closes.

Guidance and perspective are appreciated.
 
D

David Browne

Merk said:
In a 2.0 Windows Forms app... in a static class I have a method named
WriteToLocalLog() that writes to a text file on the local machine.

I declare a StreamWriter at the class level (not inside the method), as
follows:
private static System.IO.StreamWriter streamWriter_ToLocalLog;

The reason I declare streamWriter_ToLocalLog at the class level and not
inside the WriteToLocalLog() method is so I can reuse the StreamWriter
between calls to WriteToLocalLog().

My question:
Is there an obvious problem or risk with doing it this way? I'm wondering
if I would need to specifically .Close() it... else risk a memory leak or
otherwise tie up system resources once the app closes.

Guidance and perspective are appreciated.

The StreamWriter will be destroyed when your application closes, which is
apparently what you want. However, you should synchronize access to the
shared StreamWriter in case it's accessed from multiple threads.

David
 

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