Tracking Process Runtime with Enhanced .NET Techniques
Simply using Process.GetProcessesByName
offers only a momentary view of active processes; it's insufficient for tracking a process's execution duration across multiple instances. A more robust solution is needed.
Leveraging WMI for Accurate Process Monitoring
Windows Management Instrumentation (WMI) provides a powerful mechanism for detailed system event monitoring, including the precise start and end times of processes. The following C# code demonstrates WMI's application for this purpose:
<code class="language-csharp">using System; using System.Management; public class ProcessMonitor { public static void Main(string[] args) { // Watch for process start events using (ManagementEventWatcher startWatch = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"))) { startWatch.EventArrived += StartWatch_EventArrived; startWatch.Start(); // Watch for process stop events using (ManagementEventWatcher stopWatch = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace"))) { stopWatch.EventArrived += StopWatch_EventArrived; stopWatch.Start(); Console.WriteLine("Monitoring process starts and stops. Press any key to exit."); Console.ReadKey(); } } } private static void StopWatch_EventArrived(object sender, EventArrivedEventArgs e) { Console.WriteLine($"Process stopped: {e.NewEvent.Properties["ProcessName"].Value}"); } private static void StartWatch_EventArrived(object sender, EventArrivedEventArgs e) { Console.WriteLine($"Process started: {e.NewEvent.Properties["ProcessName"].Value}"); } }</code>
Executing this code with administrator privileges allows real-time monitoring of process lifecycle events. This provides a highly accurate measurement of execution time for any process, across multiple executions. Keep in mind that intensive monitoring might impact system performance.
The above is the detailed content of How Can I Accurately Track Process Execution Time in .NET?. For more information, please follow other related articles on the PHP Chinese website!