views:

249

answers:

0

I have a Trace source object with name "MyTraceSource" in class "AppTrace" c# application.

TraceSource _traceSource = new TraceSource("MyTraceSource");

I use this TraceSource to generate trace messages. In the application/exe I have used App.config to attach a SourceSwitch and TextWriterTraceListener to the TraceSource with name "MyTraceSource".

<system.diagnostics>
<sources>
  <source name ="MyTraceSource" switchName="MySourceSwitch" >
    <listeners>
      <add name ="MyListener" type ="System.Diagnostics.TextWriterTraceListener" initializeData ="Log.txt">

      </add>
    </listeners>
  </source>
</sources>
<switches>
  <add name ="MySourceSwitch" value ="Verbose"/>
</switches>

Inside the AppTrace class finalizer if i call the close or flush method, it gives exception "Cannot access a closed file". Looks like the filestream attached with the listener is automatically removed at some point prior to the finalizer. If i do not call the close or flush, my trace is not written to the file.

  1. One solution is to flush every time a trace message is written, but that will be costly i assume.
  2. Another way might be that I close it at some point in my app when things are getting destroyed. But i feel it will be clumsy because my trace object isn't a member of any other class, as its just a singleton class which has an object exposed as static property. So i dont think its logical to dispose it from just any class, since every class uses it directly.

Is there any good solution to this problem ?