有没有办法删除Thread Sleep代码?

时间:2017-07-24 04:53:02

标签: c# event-log

使用下面的代码片段,我正在尝试“订阅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);
            }

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

2 个答案:

答案 0 :(得分:2)

根据MSDN,您可以使用autoresetevent对象的waitone方法。 例如: WaitOne example

答案 1 :(得分: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);