I have recently written a C# application for monitoring a selection of server applications that restarts them in the event of a crash.
The application itself is working fine. However, I have a 'gap' in my knowledge that concerns me, and I have not found a resource that adequately fills in that gap.
Using my application as an example, I am polling a system class which reports intrinsic events, specifically __instancecreationevent
and __instancedeletionevent
using a ManagementEventWatcher
and a WQL query.
Here's a partial (edited for the sake of brevity; removed error handling, UI update code, query string builder, restart timers, loggers, et cetera) example from the application:
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
}
I have two specific questions:
- Are system classes that report intrinsic events (or system classes in general), reporting events only when they are subscribed to (e.g. by using a
ManagementEventWatcher
)? - If not, how and when are the intrinsic events being consumed since they do not appear to persist between polls?