首页 > 解决方案 > 在 for 循环中迭代 EventLogEntryCollection 时出现 IndexOutOfRangeException

问题描述

我目前有一个项目,每隔 x 秒(使用 Timer 和 10000 毫秒间隔)在 Windows 上发生的事件并在某些条件下过滤它们。每次 Timer 执行 Tick 时,对应于 10 秒前的日期和小时(由于间隔)都会检查时刻事件,并执行下一个方法:

// Method that returns wanted events from an EventLogEntryCollection
private List<EventLogEntry> lastEvents(EventLogEntryCollection eventsList, DateTime minimumMoment)
{
    // Wanted events list
    // 4624: Login
    // 4634: Logout
    long[] events = new long[] { 4624, 4634 };

    // Table to return with valid events
    List<EventLogEntry> filteredEventsList = new List<EventLogEntry>();

    // Checking if there are events to filter
    if (eventsList.Count > 0)
    {
        // There are events to filter
        // Going across all events to filter
        for (int i = 0; i < eventsList.Count; i++)
        {
            // Getting the current event
            EventLogEntry event = eventsList[i];   // Line with exception

            // Checking if the current event happened in the last 10 seconds (due to the Interval)
            if (event.TimeGenerated >= minimumMoment)
            {
                // The event is valid time wise
                // Checking if the event's ID is contained in the required ID's list
                if (events.Contains(event.InstanceId))
                {
                    // The event has a valid ID
                    // Adding the event to the list
                    filteredEventsList.Add(event);
                }
            }
        }
    }

    // Returning obtained list
    return filteredEventsList;
}

该事件获取所有事件的列表(通过使用 EventLog.Entries 获得)以及必须将事件添加到过滤事件列表的日期和时间(因此必须在 10 秒前生成事件才能被“接受” )。但是,在 eventsList 迭代期间,IndexOutOfRangeException在第一次测试中生成 an,在 28000 左右,在第二次测试中,在 43 左右,两个测试中的 Count 属性在 31000 左右。¿ 有人能告诉我为什么会这样吗?

这是异常数据的屏幕截图(它是西班牙语,抱歉): IndexOutOfRange 异常数据

标签: c#event-logindexoutofrangeexception

解决方案


根据文档

EventLogEntry 对象由事件日志系统根据它们到达事件日志的时间顺序进行索引。使用 Item[Int32] 属性选择集合中的索引已知的特定事件日志条目。

遍历 EventLogEntryCollection 实例按顺序遍历每个 EventLogEntry 对象。集合是动态的,进入循环时条目的数量可能不是一成不变的。 因此,您应该使用 for each...next 循环而不是 for 循环来逐步检查与 EventLogEntryCollection 实例关联的条目,以检查整个条目集。

由于新条目会附加到现有列表中,因此单步执行集合使您能够访问在最初创建 EventLogEntryCollection 之后创建的条目。

此外,Count的文档指出:

EventLogEntryCollection 表示日志中所有条目的动态列表。因此,Count 属性可以在您创建的 EventLogEntryCollection 实例的生命周期内更改。通常最好直接使用 Count 属性,而不是将其值分配给变量。

因此,简而言之,它Count正在发生变化(可能会减少) - 导致您查找不再存在的索引。使用foreach而不是for将为您解决此问题。


推荐阅读