大多数TraceSource
跟踪示例显示了它是如何通过配置完成的。我正在尝试通过代码来实现这一点。
我有一个简单的组装如下:
using System;
using System.Diagnostics;
using System.Threading;
namespace TracingLib
{
public class AppTracer
{
public event EventHandler AppStarted;
public event EventHandler AppStopped;
private bool CancelRequested = false;
public void Start()
{
Thread thread = new Thread(new ThreadStart(() =>
{
if(AppStarted != null) AppStarted(this, new EventArgs());
TraceSource ts = new TraceSource("ThreadSource");
ts.TraceInformation("Thread Begins");
//ts.Flush();
int i = 0;
while (!CancelRequested)
{
ts.TraceInformation("i: {0}", i++);
//ts.Flush();
Debug.Print("i : {0}", i);
Thread.Sleep(5000);
}
if (AppStopped != null) AppStopped(this, new EventArgs());
}));
thread.Start();
}
public void Stop()
{
CancelRequested = true;
}
}
}
我在控制台应用程序中使用它。
using System;
using System.Threading;
using TracingLib;
namespace caTracingLibImplementation
{
class Program
{
static void Main(string[] args)
{
AppTracer tracer = new AppTracer();
ManualResetEvent waiter = new ManualResetEvent(false);
tracer.AppStopped += (sender, e) =>
{
waiter.Set();
};
TraceSource ts = new TraceSource("ThreadSource");
ts.Listeners.Add(new ConsoleTraceListener());
var sw = new SourceSwitch("foo");
sw.Level = SourceLevels.Warning;
ts.Switch = sw;
tracer.Start();
Console.WriteLine("AppTracer started...");
Thread.Sleep(10000);
tracer.Stop();
Console.WriteLine("AppTracer stopped...");
Console.WriteLine("Waiting to stop...");
waiter.WaitOne();
Console.WriteLine("End of program");
}
}
}
如果我尝试通过控制台应用程序启用跟踪,我将看不到跟踪消息。