开发者

write to TraceListener from multiple threads

开发者 https://www.devze.com 2023-02-05 08:11 出处:网络
I have a custom TraceListener and two threads. Trace messages only come through from the first thread and the second thread\'s Trace.Write() messages do not come through. I\'ve tried using a single, g

I have a custom TraceListener and two threads. Trace messages only come through from the first thread and the second thread's Trace.Write() messages do not come through. I've tried using a single, global TraceListener that both threads have access to, but the second thread still does not produce any output.

How do I implement this so that both threads write to the same Trace output? If the trace listener utilizes locking appropriately, is it possible to do?

void Initialize()
{
    Trace.Listeners.Add(App.CustomTraceListener);
    Trace.Write("test?"); // this produces output
    var start = new ThreadStart(Run);
    var thread = new Thread(start);
    thread.Start();
}

void Run()
{
    while(true)
    {
      Threa开发者_开发技巧d.Sleep(1000);
      Trace.Write("hello from second thread"); // this does not produce anything
    }
}


Also adding Trace.AutoFlush = true also works out well.


Call Trace.Flush(); after thread.Start(); or inside Run(); and you'll see the output.

0

精彩评论

暂无评论...
验证码 换一张
取 消