【问题标题】:Multithreaded Interaction with windows EventLog与windows EventLog的多线程交互
【发布时间】:2011-04-07 22:54:01
【问题描述】:

我有两个进程 A 和 B。

进程 A 继续每 5 秒写入一次 EventLogEntry。

进程 B 应监听 EventLog 对象上的 EntryWritten 事件,并尽快在屏幕上报告已写入条目。

如何创建应该一直运行直到手动关闭的进程 B. (exe)。

请看以下代码sn-p:

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

怎么做?

谢谢。

【问题讨论】:

    标签: c# multithreading event-log


    【解决方案1】:

    您应该在log_EntryWritten 处理程序中删除对Console.ReadLine 的调用。否则你会阻塞处理程序。

    为避免您的程序立即终止,您必须在Main 末尾添加此代码:

    Console.ReadKey();
    

    在控制台上按下某个键之前,您的主线程会一直阻塞。 EventLog 类用于服务EventWritten 事件的线程将用于在每次新事件到达时执行您的处理程序。除非您必须研究来自Event.EventWritten Event 的这句话,其中包含一些关于您的 5 秒要求的信息:

    仅当最后一次写入事件发生在至少六秒之前,系统才会响应 WriteEntry。这意味着您将仅在六秒的时间间隔内收到一个 EntryWritten 事件通知,即使发生多个事件日志更改也是如此。如果您在对 WriteEntry 的调用之间插入足够长的睡眠间隔(大约 10 秒),那么您错过事件的可能性就会降低。但是,如果写入事件更频繁地发生,您可能要等到下一个时间间隔才会收到事件通知。通常,错过的事件通知不会丢失,而是延迟。

    【讨论】:

      【解决方案2】:

      你可以试试这样的简单方法:

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

      【讨论】:

        猜你喜欢
        • 2015-07-27
        • 2010-12-09
        • 2012-05-06
        • 1970-01-01
        • 1970-01-01
        • 2016-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多