Quickly opening and closing System.IO.StreamWriter in C #

Suppose you have a file in which you programmatically log information regarding a process. As usual, your typical debug Console.WriteLine, but due to the nature of the code you are testing, you do not have a console for writing, so you need to write it somewhere, like a file. My current program uses System.IO.StreamWriter for this task.

My question is about the approach to using StreamWriter. Is it better to open only one StreamWriter instance, do all the recordings and close it when the whole process is complete? Or is it better to open a new StreamWriter instance to write a line to a file, then close it immediately and do it every time something needs to be written? In the latter approach, this is likely to be facilitated by a method that will do just that for a given message, rather than inflate the main process code with an excessive number of lines. But having a way to help with this implementation does not necessarily make it a better choice. Are there any significant advantages to choosing one approach or another? Or are they functionally equivalent, leaving the choice to the programmer?

+3
source share
3 answers

Reopening / closing a new StreamWriter for each record will result in a large amount of resources for the GC plus application overhead due to the actual file search for each open operation. On the other hand, when you open one stream, the file lock will be stored. So it depends.

You do not want your logging engine to become a performance bottleneck, so write in one thread. Make it unbuffered or AutoFlush for critical debugging (but keep in mind that this also affects performance).

log4net, . log4net , . http://logging.apache.org/log4net/index.html

0

; . , , , , IO. , /.

+4

/ , / .

, ...

.

+1

Source: https://habr.com/ru/post/1742303/


All Articles