我用自己的dll来做我的阅读和写作。阅读准则:
public static EventLog getEventLog(string Source, string Log)
{
using(EventLog ev = new EventLog(Log, System.Environment.MachineName, Source))
{
if (ev.Entries.Count <= 0)
{
return null;
}
else
{
return ev;
}
}
}
以下是我用来处理事件日志的代码
private void ProcessEvents()
{
using (EventLog ev = EventComms.EventComms.getEventLog("Application", "Application"))
{
for (int i = ev.Entries.Count - 1; i >= ev.Entries.Count; i--)
{
EventLogEntry CurrentEntry = ev.Entries[i];
Console.WriteLine("Event ID : " + CurrentEntry.InstanceId);
Console.WriteLine("Entry Type : " + CurrentEntry.EntryType.ToString());
Console.WriteLine("Message : " + CurrentEntry.Message + "\n");
}
}
}
现在,当我尝试使用返回的Log执行某些操作时,我会收到(ObjectDisposedException was unhandled Message=Cannot access a disposed object.)
个异常。
当我使用ev.Entries.Count
为什么我会收到错误,处理错误的最佳方法是什么?
答案 0 :(得分:2)
您正在EventLog
方法中处理返回的getEventLog
对象。删除using
语句。实际上,getEventLog
方法可以返回null
,您不会在以后查看。我建议将所有方法放在一起并使用此代码(我也改变了循环方式):
private void ProcessEvents()
{
using (EventLog ev = new EventLog("Application", System.Environment.MachineName, "Application"))
{
for (int i = ev.Entries.Count - 1; i >= 0; i--)
{
EventLogEntry CurrentEntry = ev.Entries[i];
Console.WriteLine("Event ID : " + CurrentEntry.InstanceId);
Console.WriteLine("Entry Type : " + CurrentEntry.EntryType.ToString());
Console.WriteLine("Message : " + CurrentEntry.Message + "\n");
}
}
}
答案 1 :(得分:0)
getEventLog
函数处理 EventLog
对象(using
语句一旦返回就会自动处理它。)
尝试以下等效代码:
private void ProcessEvents()
{
using (EventLog ev = new EventLog("Application", System.Environment.MachineName, "Application"))
{
if (ev.Entries.Count <= 0))
{
return;
}
for (int i = ev.Entries.Count - 1; i >= ev.Entries.Count; i--)
{
EventLogEntry CurrentEntry = ev.Entries[i];
Console.WriteLine("Event ID : " + CurrentEntry.InstanceId);
Console.WriteLine("Entry Type : " + CurrentEntry.EntryType.ToString());
Console.WriteLine("Message : " + CurrentEntry.Message + "\n");
}
}
}