Scope of StreamWriter in Static Class; resource usage implications

  • Thread starter Thread starter Merk
  • Start date Start date
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.
 
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
 
Back
Top