Where to dispose StreamWriter if I need it during entire application lifetime? I’m going to dispose it in destructor, will that work? I have to dispose to flush data, and I don’t want to use AutoFlush feature because from msdn: "You can get better performance by setting AutoFlush to false, assuming that you always call Close (or at least Flush) when you're done writing with a StreamWriter."
So should i Dispose in destructor like in the code below?
class Log
{
private static StreamWriter swLog = new StreamWriter("logMAIN.txt");
static ~Log()
{
swLog.Dispose();
}
public static void Push(LogItemType type, string message)
{
swLog.WriteLine(type + " " + DateTime.Now.TimeOfDay + " " + message);
}
}
upd instead of Dispose i meant to call Close but it is not improtant in this case because they seems doing exactly the same.
You seem to be basing your decision not to flush on some performance information from MSDN. That’s not where I’d start.
Do you have evidence that using AutoFlush causes you significant performance problems?
Have you considered alleviating these performance problems in a different way, e.g. having a single thread writing to the
StreamWriter, either auto-flushing or periodically flushing every 20 seconds or whatever?You haven’t told us what kind of application you’re writing, mind you – that can make a significant difference in terms of how much you know about shutdown.
Also note that the code you’ve given isn’t thread-safe to start with. You could end up using the
StreamWriterfrom multiple threads concurrently; I doubt thatStreamWriteris particularly designed for that scenario.