简体   繁体   中英

Reacting to a process beginning termination

Question born of curiosity here:

How would I go about being notified or polling, to see when a process is currently being terminated?

So my application could listen out for a "termination begin" event from a process, for example, to track how long a particular process takes to close on average?

Note, this isn't in conjunction with my process flipping the kill switch, that would be simple yes, but my application would act only as an observer.

Any help would be greatly appreciated :)

The only way I know for you to do this without polling is through WMI. There are plenty of examples on the web, eg Using WMI to monitor process creation, deletion and modification in .NET .

WMI is well wrapped by the .net libraries. For example, the sample above uses ManagementEventWatcher to subscribe to WMI events. There's a whole treasure trove of WMI goodness in the System.Management namespace.

I'm not really sure if there is a way for this to be a "push" operation (you somehow get notified of the ending process).

But what I would do to mimick this observation is to create a Windows Service that polls the process on a specified interval (say, every 2 seconds or however much latency is acceptable for you). That way you can handle the situation when the other process ends and act accordingly.

I am not sure if there is a WIN32 API for subscribing to events of the process terminated but you can do the polling simply by getting the list of processes running:

 var processes = System.Diagnostics.Process.GetProcesses();

I would use the ProcessId as the key for my dictionary to check when it is started and when it is terminated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM