有没有办法删除线程睡眠代码?



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

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

根据 MSDN,您可以使用 waitone 方法的自动重置事件对象。 例如: 等待一个例子

无论如何,控制台将结束,因此您可能希望运行直到用户说停止。

因此,替换睡眠代码行:

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);