use a static StreamWriter?

G

gol

Hi,
I'm writing an application that needs every so often to write some data to a
text file (some kind of a log file). I don't write a lot of data to the text
file – just about 10 times, about 100 bytes each time, that's a total of
approximately 1K, during a total period of approximately 2 minutes.

My question is whether I should open a StreamWriter each time, this way I
can write something like:

using (StreamWriter sw…)
{
sw.WriteLine(…);
}

Or is it better to define some static StreamWriter, which I will not close
until the end of the program. I hope I will always be able to detect an
unexpected exit, and then close the StreamWriter, but I'm not sure about it.

What I like in the first method is using the "using" keyword, which is
impossible in the second.
Can anyone tell what is better in my situation? What are the advantages and
disadvantages of each method?
Thanks a lot
 
B

Brian Gideon

Hi,
I'm writing an application that needs every so often to write some data to a
text file (some kind of a log file). I don't write a lot of data to the text
file – just about 10 times, about 100 bytes each time, that's a total of
approximately 1K, during a total period of approximately 2 minutes.

My question is whether I should open a StreamWriter each time, this way I
can write something like:

using (StreamWriter sw…)
{
     sw.WriteLine(…);

}

Or is it better to define some static StreamWriter, which I will not close
until the end of the program. I hope I will always be able to detect an
unexpected exit, and then close the StreamWriter, but I'm not sure about it.

What I like in the first method is using the "using" keyword, which is
impossible in the second.
Can anyone tell what is better in my situation? What are the advantages and
disadvantages of each method?
Thanks a lot

I'm not sure it's going to make a whole lot of difference since you're
only talking about a few writes with small data amounts. But, I can
you that I tend to hold resources open for the entire unit of work.
Assuming the 2 minute figure you mentioned represents one logical unit
of work then I would I recommend holding the StreamWriter open for the
entire period. You can still use the 'using' keyword as long as you
have the code structured accordingly.
 

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