2011-04-07 104 views
0

我有兩個進程A和B.與Windows的多線程交互EventLog

進程A繼續每5秒寫入一次EventLogEntry。

進程B應該偵聽EventLog對象上的EntryWritten事件,並儘快在屏幕上報告已寫入條目。

如何創建應始終運行直到手動關閉的進程B.(exe)。

請參見下面的代碼片段:

class Observer 
{ 
    static void Main(string[] args) 
    { 
     EventLog log = new EventLog("logname", "MyMachine", "source"); 

     log.EntryWritten += new EntryWrittenEventHandler(log_EntryWritten); 
     log.EnableRaisingEvents = true; 

     // The thread shouldn't exit here but wait till the event is received 
     // When received, should call the handler 
     // and then again keep waiting for next event. 
    } 

    static void log_EntryWritten(object sender, EntryWrittenEventArgs e) 
    { 
     if (e.Entry.Source == "source") 
     { 
      Console.WriteLine("Message " + e.Entry.Message); 
      Console.WriteLine("InstanceId " + e.Entry.InstanceId); 
      Console.WriteLine("Source " + e.Entry.Source); 
      Console.WriteLine("TimeWritten " + e.Entry.TimeWritten); 

      Console.ReadLine(); 
      Console.WriteLine("\n"); 
     } 
    } 
} 

如何能不能做到?

謝謝。

回答

1

您應該刪除調用Console.ReadLinelog_EntryWritten處理。否則,你會阻止處理程序。

爲避免你的程序馬上就得在Main末尾添加以下代碼終止:

Console.ReadKey(); 

你的主要THEAD將阻塞,直到一個鍵被按下控制檯上。 EventLog類用於服務EventWritten事件的線程將用於每次新事件到達時執行處理程序。除非你必須學習從Event.EventWritten Event這句話有一些信息,你5秒要求:

的系統響應WriteEntry只有在發生至少六秒鐘,最後寫事件之前。這意味着即使發生多個事件日誌更改,您也只會在6秒內收到一個EntryWritten事件通知。如果在WriteEntry調用之間插入足夠長的睡眠間隔(大約10秒),則不太可能錯過某個事件。但是,如果寫入事件頻繁發生,則可能會在下一個時間間隔之前收到事件通知。通常,錯過的事件通知不會丟失,但會延遲。

1

你可以嘗試一些簡單的像這樣:

static void Main(string[] args) 
{ 
    EventLog log = new EventLog("logname", "MyMachine", "source"); 

    log.EntryWritten += new EntryWrittenEventHandler(log_EntryWritten); 
    log.EnableRaisingEvents = true; 

    //Wait for a key to be pressed. 
    Console.ReadKey(); 
}