C# 动态列表到静态列表

标签 c# event-log

根据事件日志类的文档,EventLogEntryCollection 是事件日志条目的动态列表。它建议直接使用 Count 属性,而不是将其值存储在变量中。实现此行为:

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
}

对于大型事件日志(>20000 个条目)来说速度很慢。使用 for 循环而不是 foreach 的原因是因为我需要迭代器位置来指示这件事距离完成有多近。

存储计数变量并迭代它:

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

提供显着的性能提升。但是,如果在处理发生时写入事件日志,则可能会出现索引超出范围异常。有没有办法静态存储这个列表,这样计数就不会改变?

最佳答案

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

听起来你想要类似的东西:

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

这会将所有日志条目(当时)提取到 List<T> 中,然后可以使用索引器或另一个 foreach 快速访问。 .

当然,您可能会发现仅获取所有日志条目就很慢 - 您应该尝试一下。

关于C# 动态列表到静态列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23787672/

相关文章:

powershell - 在PowerShell中从事件日志中过滤最后 “boot event”的ID

c# - 检查一个字符串是否已经添加到列表中 c#

c# - C# 控制台应用程序中的单线程异步/等待

c# - 为什么未使用的重载需要项目引用?

iis - 如何授予 ApplicationPoolIdentity 写入应用程序事件日志的权限?

c# - 在事件查看器中写入应用程序日志

c# - 使用 c# lambdas 进行递归非二进制、非排序树搜索

c# - 直接解析子串为double

c# - 如何记录严重级别的事件日志?