我编写了一些代码来监视正在运行的 Windows 进程。我想知道某个过程何时开始以及何时结束。代码就像我想要的那样工作。
现在,我希望在 Windows 表单服务器应用程序中实现它——所以只要表单还活着,它就会循环运行。我想我应该让它异步运行,也许使用BackgroundWorker
. 我只是不确定什么是最好的方法以及如何做到这一点。
这是我的监控代码:
using System;
using System.Management;
using System.Diagnostics;
using System.Collections.Generic;
using System.ComponentModel;
class ProcessMonitor
{
public static void Main()
{
Dictionary<string, Process> newProcs= new Dictionary<string, Process> ();
while (true)
{
foreach (Process process in Process.GetProcesses())
{
if (process.ProcessName.CompareTo("Someprocess") == 0)
{
if (!searchForProcess(newProcs, process.Id))
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + process.Id);
foreach (ManagementObject @object in searcher.Get())
{
Console.Write("Adding new Process: ");
Console.WriteLine(@object["CommandLine"] + " ");
newProcs.Add(@object["CommandLine"] + " ", process);
}
}
}
}
checkProcesses(newProcs);
}
Console.WriteLine("Done");
}
private static bool searchForProcess(Dictionary<string, Process> newProcs, int newKey)
{
foreach (Process process in newProcs.Values)
{
if (process.Id == newKey)
return true;
}
return false;
}
private static void checkProcesses(Dictionary<string, Process> newProcs)
{
foreach (string currProc in newProcs.Keys)
{
bool processExists = false;
foreach (Process process in Process.GetProcesses())
{
if (process.Id == newProcs[currProc].Id)
{
processExists = true;
break;
}
}
if (!processExists)
{
Console.Write("Process Finished: ");
Console.WriteLine(currProc);
newProcs.Remove(currProc);
if (newProcs.Count == 0)
break;
}
}
}
}
有任何想法吗?