如何订阅资源耗尽诊断事件?

时间:2013-09-17 17:41:47

标签: c# windows event-handling

我想知道Windows 7何时检测到我的程序使用了太多内存。所以我想处理这个。我如何订阅此活动(申请将被关闭前)。

Windows日志中的一些信息:

  

Windows成功诊断出虚拟内存不足的情况。以下程序消耗的虚拟内存最多。   事件编号:2004   关键字:与系统提交限制(虚拟内存)耗尽相关的事件。

Detecting Low Virtual Memory Conditions in Windows

1 个答案:

答案 0 :(得分:2)

System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog("System", ".", "Resource-Exhaustion-Detector");
eventLog.EnableRaisingEvents = true;
eventLog.EntryWritten += eventLog_EntryWritten;

static void eventLog_EntryWritten(object sender, System.Diagnostics.EntryWrittenEventArgs e)
{
   if (e.Entry.Message.Contains(Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName)))
   {
      Logger.Error("Our application consumed too much memory `{0}`. So we stopping work right now to prevent reboot OS.", new object[] {e.Entry.Message},MethodBase.GetCurrentMethod());
      GC.Collect();
      //do smth                
   }
}