C# Dynamic List to Static List

From the documentation of the Event Log Class the EventLogEntryCollection is a dynamic list of event log entries. It recommends that the Count property is used directly instead of storing its value in a variable. Implementing this behavior:

private void ReadEventLog()
{
    EventLog eventLog = new EventLog("Application", "TheGreatestMachineInTheWorld");
    EventLogEntryCollection eventLogEntries = eventLog.Entries;
    for (int i = 0; i < eventLogEntries.Count; i++){
        EventLogEntry entry = eventLog.Entries[i];
        //Do Some processing on the entry
}

Is slow for large event logs ( >20000 entries). The reason for the for loop instead of a foreach is because I need the iterator location to indicate how close this thing is to finishing.

Storing the count variable and iterating over that:

int eventLogEntryCount = eventLogEntries.Count;
for (int i = 0; i < eventLogEntryCount; i++){
        EventLogEntry entry = eventLog.Entries[i];
        //Do Some processing on the entry
}

Provides a noticeable performance boost. However it opens the possibility for an index out of range exception if the event log is being written to as the processing happens. Is there a way to store this list statically so the count does not change?

Jon Skeet
people
quotationmark

Is there a way to store this list statically so the count does not change?

It sounds like you want something like:

List<EventLogEntry> entries = eventLogEntries.Cast<EventLogEntry>().ToList();

That will fetch all the log entries (at that time) into a List<T>, which will then be quick to access either with the indexer or with another foreach.

Of course, you may find it's slow just to fetch all the log entries - you should experiment with that.

people

See more on this question at Stackoverflow