如何解决从事件日志中获取事件的详细信息
| 我试图基于列表框中项目的选择从事件日志中获取详细信息。我试图将详细信息放入文本框。我已经成功地找到了自己的解决方案。我所做的事情(而且非常慢)是在事件日志中重申并找到与日志索引的匹配项,然后显示消息,但这是一项耗时的操作。有没有一种更快的方法可以根据日志索引直接到达特定的日志条目。我正在使用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挂起的原因,但是即使我将其设置在其他线程上,就像我在将项目添加到列表框中时所做的那样,仍然需要一些时间来完成所有操作才能获得我正在寻找确切的索引。因此,Im真正想做的只是直接进入该索引并获取消息,而不是遍历整个列表进行搜索。
解决方法
查看您的代码后,以下是我的简要操作:
卸下
ProgressChanged
装卸器。它旨在向用户报告当前状态,而您不会这样做。而是在DoWork
处理程序中调用Items.Add
。
一次创建EventLog
。这看起来似乎更好,并且如果您不小心的话,可以避免您可能在循环中创建它。
与其使用正则表达式解析文本,不如创建一个特殊的类。这确实很重要,当您需要更准确的行为或根本不希望显示索引时,将为您节省很多痛苦。正则表达式很慢,并且绝不能解析要显示给用户的数据。您必须使用类。
使用有意义的名称。我知道您没有清理代码,但是如果您希望有人通过Internet来帮助您,那么您确实应该这样做。
最后,按索引获取项目。如果查看文档,您会注意到有一个indexer属性,该属性直接通过其索引获取项目。
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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。