我正在使用System.Timers.Timer
检查某个进程是否以1000毫秒的间隔运行,如果是,则将其输出到字符串上,例如:
System.Timers.Timer bTimer = new System.Timers.Timer();
bTimer.Elapsed += new ElapsedEventHandler(ChangeText);
bTimer.Interval = 1000;
bTimer.Enabled = true;
private void ChangeText(object source, ElapsedEventArgs e)
{
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.Contains("notepad"))
{
lblText.Text = "Notepad is running.";
}
else
{
lblText.Text = "Notepad is not running.";
}
}
}
现在我想知道,有没有更有效的方法来做这个,没有计时器?例如,监控正在运行的进程而不必每秒读取内存的东西?
答案 0 :(得分:1)
var process = Process.GetProcessesByName("notepad").FirstOrDefault();
if (process == null)
{
MessageBox.Show("process is not running");
}
else
{
process.EnableRaisingEvents = true;
process.Exited += (sender, args) =>
{
MessageBox.Show("process exited");
};
}