[英]Multithreaded Interaction with windows EventLog
我有两个进程A和B.
进程A每5秒继续写EventLogEntry。
进程B应该在EventLog对象上侦听EntryWritten事件,ASAP应该在屏幕上报告已经写入了一个条目。
如何创建应该一直运行的Process 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");
}
}
}
如何做呢?
谢谢。
您可以尝试这样简单的事情:
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();
}
您应该在log_EntryWritten
处理程序中删除对Console.ReadLine
的调用。 否则你将阻止处理程序。
为避免程序立即终止,您必须在Main
的末尾添加此代码:
Console.ReadKey();
你的主要主题将被阻止,直到在控制台上按下一个键。 EventLog
类用于为EventWritten
事件提供服务的EventWritten
将用于在每次新事件到达时执行您的处理程序。 除非您必须从Event.EventWritten事件中学习此引用, 该事件包含有关您5秒钟要求的一些信息:
仅当最后一次写入事件发生在至少六秒之前时,系统才会响应WriteEntry。 这意味着即使发生多个事件日志更改,您也只能在六秒间隔内收到一个EntryWritten事件通知。 如果在对WriteEntry的调用之间插入足够长的休眠间隔(大约10秒),则不太可能错过事件。 但是,如果更频繁地发生写入事件,则可能不会在下一个间隔之前收到事件通知。 通常,错过的事件通知不会丢失,但会延迟。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.