从事件日志获取事件的详细信息

我试图根据列表框中项目的选择从事件日志中获取详细信息。 我试图将细节放入文本框中。 我已经成功地找到了自己的解决方案。 我所做的,并且非常慢,通过事件日志重复并找到与日志索引的匹配,然后显示消息,但这是一个耗时的操作。 是否有更快的方法可以根据日志索引直接获取特定的日志条目。 我使用WPF和C#。

private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) { EventLog eventLog1 = new EventLog(); eventLog1.Log = "System"; foreach (System.Diagnostics.EventLogEntry entry in eventLog1.Entries) { var newEntry = entry.Index + " - " + entry.EntryType + " - " + entry.TimeWritten + " - " + entry.Source; backgroundWorker2.ReportProgress(0, newEntry); } } void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e) { var newEntry = (string)e.UserState; MainWindow.Instance.Dispatcher.BeginInvoke(new Action(delegate() { MainWindow.Instance.listBox1.Items.Add(newEntry); })); } 

然后使用项目的索引将每个项目添加到列表框中,然后我查看并提取索引:

 private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e) { string p1 = listBox1.SelectedItem.ToString(); string[] id = Regex.Split(p1, @"([\s])"); label1.Content = id[0]; EventLog el = new EventLog(); el.Log = "System"; foreach (System.Diagnostics.EventLogEntry entry in el.Entries) { if (entry.Index.ToString() == id[0]) { label1.Content = entry.Message; } } } 

foreach循环是导致UI挂起的原因,但即使我将它设置在不同的线程上,就像我在将项目添加到列表框时所做的那样,仍需要一些时间来完成所有操作才能获得我正在寻找的确切指数。 所以我真正想做的就是直接进入该索引并抓取消息而不是遍历整个列表来搜索它。

查看代码后,我会快速总结一下我会做什么:

删除ProgressChanged处理程序。 它用于向用户报告当前状态,您不这样做。 而是在DoWork处理程序中调用Items.Add

创建EventLog一次。 这似乎更好,如果你不小心,可以避免在循环中创建它。

而不是使用正则表达式解析文本,而是创建一个特殊的类。非常重要,当您需要更准确的行为或根本不希望显示索引时,这将为您节省很多痛苦。 正则表达式很慢,并且绝不能解析用于向用户显示的数据。 你必须使用类。

用有意义的名字。 我知道你没有清理代码,但如果你想让别人通过互联网帮助你,你真的应该这样做。

最后,按索引获取项目。 如果您查看文档 ,您会注意到有一个索引器属性直接通过其索引获取项目。

 class EntryItem { public EntryItem (EventLogEntry entry) { EntryIndex = entry.Index; ItemText = string.Format ("{0} - {1} - {2} - {3}", entry.Index, entry.EntryType, entry.TimeWritten, entry.Source); } public string ItemText { get; private set; } public int EntryIndex { get; private set; } public override string ToString () { return ItemText; } } private EventLog log = new EventLog { Log = "System" }; private void eventLoader_DoWork (object sender, DoWorkEventArgs e) { foreach (EventLogEntry entry in this.log.Entries) this.Dispatcher.BeginInvoke (() => eventListBox.Items.Add (new EntryItem (entry))); } private void eventListBox_SelectionChanged (object sender, SelectionChangedEventArgs e) { EntryItem item = eventListBox.SelectedItem as EntryItem; if (item == null) return; var entry = log.Entries [item.EntryIndex]; currentEntryLabel.Content = entry.Message; }