2017-07-24 52 views
0

使用下面的代码片段,我试图做“预订Windows事件日志”。有办法删除线程休眠代码吗?

using System; 
using System.Diagnostics.Eventing.Reader; 

namespace ConsoleApp1 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 

     EventLogWatcher watcher = null; 
     try 
     { 
      EventLogQuery subscriptionQuery = new EventLogQuery("Application", PathType.LogName, "*[System/EventID=101]"); 

      watcher = new EventLogWatcher(subscriptionQuery); 

      watcher.EventRecordWritten += new EventHandler<EventRecordWrittenEventArgs>(EventLogEventRead); 

      // Activate the subscription 
      watcher.Enabled = true; 

      for (int i = 0; i < 5; i++) 
      { 
       // Wait for events to occur. 
       System.Threading.Thread.Sleep(10000); 
      } 
     } 
     catch (EventLogReadingException e) 
     { 
      Console.WriteLine(e.Message); 
     } 
     finally 
     { 
      // Stop listening to events 
      watcher.Enabled = false; 

      if (watcher != null) 
      { 
       watcher.Dispose(); 
      } 
     } 

     Console.ReadKey(); 

    } 

    private static void EventLogEventRead(object obj, EventRecordWrittenEventArgs arg) 
    { 
     // Make sure there was no error reading the event. 
     if (arg.EventRecord != null) 
     { 
      Console.WriteLine(arg.EventRecord.TimeCreated); 
      Console.WriteLine(arg.EventRecord.FormatDescription()); 
     } 
     else 
     { 
      Console.WriteLine("The event instance was null."); 
     } 
    } 
} 
} 

在这里一切看起来不错,但有什么办法可以删除线程睡眠代码?

for (int i = 0; i < 5; i++) 
      { 
       // Wait for events to occur. 
       System.Threading.Thread.Sleep(10000); 
      } 

什么可能是其他解决方案,可以调用事件发生?

+1

是:用鼠标点击“for”以将光标置于其上,然后按住“删除”键直到有问题的代码段被删除。为了得到答案,你需要解释你需要完成什么,以及为什么你显示的代码没有完成。 –

+0

你想等待用户的停止请求吗? –

+0

你想继续等待50秒吗?或者是否有一些事件发生? – Enigmativity

回答

1

无论如何,控制台将结束,所以你可能想运行,直到用户说停止。

所以,更换睡眠代码行:

for (int i = 0; i < 5; i++) 
     { 
      // Wait for events to occur. 
      System.Threading.Thread.Sleep(10000); 
     } 

有了:

Console.WriteLine("Press the Escape (Esc) key to quit: \n"); 
do 
{ 
    cki = Console.ReadKey(); 
    // nothing to do and ready to recieve next pressed key. 
} while (true); 
+0

我想继续阅读事件日志,直到我的EXE运行 – user584018

+0

一招!只是你不检查'cki.Key!= ConsoleKey.Escape'! 如果真的让m,e知道并编辑我的答案:) –

+0

那么应该在什么时候 – user584018

2

根据MSDN,你可以使用的WaitOne的AutoResetEvent对象的方法。 例如: WaitOne example