HOW TO:記錄多執行緒元件的事件
當記錄多執行緒元件的事件時,有些特殊事項是必須列入考量的。 您必須提供方法來辨識事件來源的執行緒。 當記錄事件時,您也必須確保執行緒不會互相干擾。 如需詳細資訊,請參閱事件記錄檔和多執行緒元件。
若要在多執行緒應用程式中使用事件記錄檔
宣告並建立事件記錄檔。 如需詳細資訊,請參閱HOW TO:建立及移除自訂事件記錄檔。
將每個執行緒的 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:加入應用程式做為事件記錄檔項目來源。
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"); }
請參閱
工作
逐步解說:使用 Visual Basic 撰寫簡單的多執行緒元件