如何:记录多线程组件的事件
当记录多线程组件中的事件时,就应该考虑特殊注意事项了。 您必须提供一种方法来标识作为事件来源的线程。 还必须确保当记录事件时,线程不会互相干扰。 有关详细信息,请参见 事件日志和多线程组件。
在多线程应用程序中使用事件日志
声明并创建事件日志。 有关详细信息,请参见 How to: Create and Remove Custom Event Logs。
将每个线程的 Name 属性设置为唯一的标识符。
Dim X as Integer X = 0 Dim MyThread as New Threading.Thread(AddressOf MyMethod) MyThread.Name = "Thread number " & X.ToString ' Increments X so no other threads will share the same name. X += 1
int X; X = 0; Thread MyThread = new Thread(new ThreadStart(MyMethod)); MyThread.Name = "Thread Number " + X.ToString(); // Increments X so no other threads will share the same name. X += 1;
为事件日志创建新的 Source,并将 Name 设置为与该线程对应的唯一字符串值。 有关如何创建 Source 的详细信息,请参见 How to: Add Your Application as a Source of Event Log Entries。
Imports System.Threading ' Checks to see if there already is a source with the name of the ' thread. If Not EventLog.SourceExists(Thread.CurrentThread.Name.ToString, _ "myApplication") Then ' Creates a source with the name of the thread EventLog.CreateEventSource(Thread.CurrentThread.Name.ToString, _ "MyApplication") End If
// These lines go at the top of the code using System.Threading; using System.Diagnostics; // Checks to see if there already is a source with the name of the // thread. if (!EventLog.SourceExists(CurrentThread.Name.ToString())) // Creates a source with the name of the thread. EventLog.CreateEventSource(CurrentThread.Name.ToString(), "MyApplication");
将事件日志的 Source 属性设置为该线程的名称,然后调用 WriteEntry 方法。
备注
确保在进行这些操作之前获得事件日志上的专用锁。
' Use the SyncLock keyword to obtain an exclusive lock on an object. SyncLock MyEventLog MyEventLog.Source = Thread.CurrentThread.Name.ToString EventLog.WriteEntry(Thread.CurrentThread.Name.ToString, _ "Error in Widget 42") End SyncLock
// Use the lock keyword to obtain an exclusive lock on an object lock(MyEventLog) { MyEventLog.Source = Thread.CurrentThread.Name.ToString(); EventLog.WriteEntry(Thread.CurrentThread.Name.ToString(), "Error in Widget 42"); }
请参见
任务
参考
其他资源
How to: Create and Remove Custom Event Logs