跨线程的TraceSource不能工作
本文关键字:不能 工作 TraceSource 线程 | 更新日期: 2023-09-27 18:18:58
我想我已经失去理智了。根据MSDN, TraceSource是线程安全的。我有一个简单的控制台应用程序。在其中,我声明;
private static readonly TraceSource ActiveTraceSource = new TraceSource("Test");
在我的app.config中,有;
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add name="consoleListener" type="System.Diagnostics.ConsoleTraceListener"/>
</listeners>
</trace>
</system.diagnostics>
在main()中,我做了类似;
ActiveTraceSource.TraceInformation("Hi!");
工作很棒,我有嗨!在我的控制台上。然后我这样做;
new Thread(DoWork).Start();
在DoWork内部,我做了同样的事情;
ActiveTraceSource.TraceInformation("Hi!");
应该可以,但是我没有收到第二个"嗨!"设置一个断点显示DoWork有一个ActiveTraceSource实例,并且在集合中有一个监听器,但在控制台中没有。
这是控制台侦听器中的错误吗?我错过什么了吗?
我使用了以下配置:
<system.diagnostics>
<sources>
<source name="Test" switchValue="All">
<listeners>
<add name="consoleListener" type="System.Diagnostics.ConsoleTraceListener"/>
</listeners>
</source>
</sources>
</system.diagnostics>
测试代码:
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");
}
}
愚蠢的人做傻事。当使用跟踪源时,包含配置的一部分真的很有帮助。