Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TraceSource across threads doesn't work?

I think I've lost my mind guys.. According to MSDN, TraceSource is thread safe. So I have a simple console app. In it, I declare;

private static readonly TraceSource ActiveTraceSource = new TraceSource("Test");

In my app.config, I have;

<system.diagnostics>
    <trace autoflush="true">
      <listeners>
        <add name="consoleListener" type="System.Diagnostics.ConsoleTraceListener"/>
      </listeners>
    </trace>
  </system.diagnostics>

Inside my main(), I do something like;

ActiveTraceSource.TraceInformation("Hi!");

Works fantastic, I have Hi! on my console. Then I do this;

new Thread(DoWork).Start();

Inside DoWork, I do the same thing;

ActiveTraceSource.TraceInformation("Hi!");

Should work, but I don't get the second 'Hi!'.. Setting a breakpoint shows me that DoWork has an instance of ActiveTraceSource, and there is a listener in the collection, but nothing in the console.

Is this a bug in the console listener? Am I missing something?

like image 859
XeroxDucati Avatar asked Sep 19 '26 00:09

XeroxDucati


1 Answers

I used following config.

<system.diagnostics>
    <sources>
      <source name="Test" switchValue="All">
        <listeners>
          <add name="consoleListener" type="System.Diagnostics.ConsoleTraceListener"/>
        </listeners>
      </source>
    </sources>    
  </system.diagnostics>

Test Code:

class Program
        {
        private static readonly TraceSource ActiveTraceSource = new TraceSource("Test"); 
        static void Main(string[] args)
            {

            ActiveTraceSource.TraceInformation("Hi");
            Thread th = new Thread(new ThreadStart(Test));
            th.Start();
            Console.ReadLine();
            }

        static void Test()
            {
            ActiveTraceSource.TraceInformation("Hi");
            }
        }

It works for me in thread as well.

like image 63
dotnetstep Avatar answered Sep 20 '26 13:09

dotnetstep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!