Reputation: 20708
Sorry if I miss it somewhere, but I cannot find any documentation if a TraceListener
is automatically disposed by the framework.
If I use this code:
var traceListener = new DailyTraceListener("Logs", true);
Trace.Listeners.Add(traceListener);
Do I need to manually call traceListener.Dispose()
, assuming Dispose
should be called for it to work properly? Note that the implementation will throw error if Dispose
is called the 2nd time (I am trying to change it).
In this article:
The listeners are disposed by the TraceSource
What/Where is the TraceSource
in this case? Is it automatically disposed?
In short, is Dispose
guaranteed to be called by .NET when the program exits?
Upvotes: 1
Views: 193
Reputation: 20708
I did the test by myself. Seem like it is never called naturally. This is the demo code:
class Program
{
static void Main(string[] args)
{
var listener = new TestTraceListener();
Trace.Listeners.Add(listener);
Trace.WriteLine("Test");
listener.Dispose();
Trace.WriteLine("After dispose");
}
}
public class TestTraceListener : TraceListener
{
public override void Write(string message)
{
File.AppendAllText("log.log", message);
}
public override void WriteLine(string message)
{
this.Write(message + Environment.NewLine);
}
protected override void Dispose(bool disposing)
{
this.WriteLine("Dispose called");
base.Dispose(disposing);
}
~TestTraceListener()
{
this.WriteLine("Destructor called");
}
}
My text file is:
Test
Dispose called
After dispose
After that, I try removing the Dispose
call (// listener.Dispose();
), this is the result:
Test
After dispose
Conclusion: Dispose
is not called by default if the program exit naturally.
Upvotes: 1