Reputation: 3291
I'm using a System.Timers.Timer
to check if a certain process is running on an interval of 1000ms, and if so, to output it on a string, e.g.:
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.";
}
}
}
Now I was wondering, is there a more efficient way to do this, without a timer? For example something that monitors running processes without having to read the memory every second?
Upvotes: 2
Views: 140
Reputation: 116128
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");
};
}
Upvotes: 1