共用方式為


如何:記錄多執行緒元件的事件

當記錄多執行緒元件的事件時,有些特殊事項是必須列入考量的。 您必須提供方法來辨識事件來源的執行緒。 當記錄事件時,您也必須確保執行緒不會互相干擾。 如需詳細資訊,請參閱事件記錄檔和多執行緒元件

若要在多執行緒應用程式中使用事件記錄檔

  1. 宣告並建立事件記錄檔。 如需詳細資訊,請參閱How to: Create and Remove Custom Event Logs

  2. 將每個執行緒的 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;
    
  3. 為事件記錄檔建立新 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");
    
  4. 將事件記錄檔的 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 撰寫簡單的多執行緒元件

逐步解說:使用 Visual C# 撰寫簡單的多執行緒元件

參考

SyncLock 陳述式

其他資源

How to: Create and Remove Custom Event Logs

How to: Write Entries to Event Logs

元件中的多執行緒