有办法删除线程休眠代码吗?
使用下面的代码片段,我试图做“预订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);
}
什么可能是其他解决方案,可以调用事件发生?
无论如何,控制台将结束,所以你可能想运行,直到用户说停止。
所以,更换睡眠代码行:
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);
我想继续阅读事件日志,直到我的EXE运行 – user584018
一招!只是你不检查'cki.Key!= ConsoleKey.Escape'! 如果真的让m,e知道并编辑我的答案:) –
那么应该在什么时候 – user584018
是:用鼠标点击“for”以将光标置于其上,然后按住“删除”键直到有问题的代码段被删除。为了得到答案,你需要解释你需要完成什么,以及为什么你显示的代码没有完成。 –
你想等待用户的停止请求吗? –
你想继续等待50秒吗?或者是否有一些事件发生? – Enigmativity