[.NET] - EventLog.EntryWritten Event

刚看到在MSND论坛上有人问一个EventLog.EntryWritten Event相关的问题,说是在2015触发了一个2013年的EventWritten的事件,比较好奇,然后查看了下这个类:

https://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.entrywritten%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

在的Remarks里看到有这么一段话:

The system responds to WriteEntry only if the last write event occurred at least six seconds previously. This implies you will only receive one EntryWritten event notification within a six-second interval, even if more than one event log change occurs. If you insert a sufficiently long sleep interval (around 10 seconds) between calls to WriteEntry, you are less likely to miss an event. However, if write events occur more frequently, you might not recieve the event notification until the next interval. Typically, missed event notifications are not lost, but delayed.

意思大概是这个时间只会在6秒内触发一次,如何将两次调用WriteEntry的时间间隔大于6s,那就不会造成事件miss,只是会被延迟。写了一个程序来测试下:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace P20150409
{
    class Program
    {
        static void Main(string[] args)
        {
            EventLog myNewLog = new EventLog("Application", ".", "dotNET Sample App");

            myNewLog.EntryWritten += new EntryWrittenEventHandler(MyOnEntryWritten);
            myNewLog.EnableRaisingEvents = true;
            while (true)
            {
                System.Threading.Thread.Sleep(3000);
                string EventWriteTime = DateTime.Now.ToString();
                Console.WriteLine("Log is written at" + EventWriteTime);
                myNewLog.WriteEntry("Test message written at" + EventWriteTime + " " + System.Threading.Thread.CurrentThread.ManagedThreadId, EventLogEntryType.Information);
                Console.WriteLine();
            }
            Console.ReadLine();
        }

        private static void MyOnEntryWritten(object sender, EntryWrittenEventArgs e)
        {
            System.Threading.Thread.Sleep(6000);
            Console.WriteLine("EntryWritten event is fired at" + DateTime.Now.ToString());
            Console.WriteLine("Log time is" + e.Entry.Message);
            Console.WriteLine();
        }
    }
}

 以下是输出结果:

可以看到事件确实是没有被miss,而且触发的那次call EntryWrite方法与当前call EntryWrite的时间间隔越来越大,也就是说,这是有可能在两年后触发该事件。。。):

但是在把事件里的线程睡眠代码去掉后,事件是实时触发的,所谓的6s时间间隔内的限制并没有体现出来,不知道是不是测试的方式不对,还是系统的设置问题。如各位有知道,请指导下。

posted @ 2015-04-09 20:03  码农小包  阅读(700)  评论(0编辑  收藏  举报