我最近编写了一个C#应用程序,用于监视一系列服务器应用程序,这些应用程序在发生崩溃时重新启动它们 .
应用程序本身工作正常 . 但是,据我所知,我有一个与我有关的“差距”,而且我还没有找到足够填补这一差距的资源 .
以我的应用程序为例,我正在使用 ManagementEventWatcher
和WQL查询轮询报告内部事件的系统类,特别是 __instancecreationevent
和 __instancedeletionevent
.
以下是应用程序中的部分(为简洁起见而编辑;删除了错误处理,UI更新代码,查询字符串构建器,重启定时器, Logger 等)示例:
private void Main_Load(object sender, EventArgs e)
{
// _watchers[0] holds "__InstanceCreationEvent" watcher
_watchers[1] = new ManagementEventWatcher(new WqlEventQuery("__InstanceDeletionEvent", new TimeSpan(0,0,5), "TargetInstance ISA 'Win32_Process' AND TargetInstance.Name = 'application.exe'"));
_watchers[1].EventArrived += new EventArrivedEventHandler(Watcher_EventArrived);
_watchers[1].Start();
}
private void Watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
ManagementBaseObject process = (ManagementBaseObject)e.NewEvent["TargetInstance"];
String executablePath = process["ExecutablePath"].ToString();
ApplicationInfo app = _monitoredApps.SingleOrDefault(app => app.Key.ToLower() == executablePath.ToLower()).Value;
switch (e.newEvent.ClassPath.ClassName)
{
case "__InstanceCreationEvent": // process has started/been opened
{
// UI updates to show process id, session id and status
break;
}
case "__InstanceDeletionEvent": // process has been terminated
{
Restart(app);
break;
}
}
}
private void Restart(ApplicationInfo appInfo)
{
// UI updates
// Checks that the app isn't already running e.g. started by user before timer elapsed
Process process = new Process();
process.StartInfo.WorkingDirectory = appInfo.ExecutablePath;
process.StartInfo.FileName = appInfo.ProgramName;
process.Start(); // Elevated privileges not required
}
我有两个具体问题:
-
系统类是否报告内部事件(或一般的系统类),仅在订阅时报告事件(例如,使用
ManagementEventWatcher
)? -
如果没有,内部事件如何以及何时被消耗,因为它们似乎不会在民意调查之间持续存在?