【发布时间】:2017-09-28 02:13:54
【问题描述】:
我正在检查一个进程是否正在运行,如果没有启动该进程。 它工作正常,但只有一次,之后,语句完成并且不再运行,这是预期的。
但我不知道如何每 X 秒运行一次。
这是我的代码:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
while (checkBox1.Checked)
{
var retVal = Process.GetProcesses().Any(p => p.ProcessName.Contains(textBox1.Text));
if (retVal.Equals(true))
{
listBox1.Items.Add(textBox1.Text + @" " + @"is running." + @" " + DateTime.Now);
return;
}
if (retVal.Equals(false))
{
listBox1.Items.Add(textBox1.Text + @" " + @"is not running, attempting to start." + DateTime.Now);
Process.Start(textBox2.Text);
return;
}
}
}
现在我知道每个 if 语句末尾的 return 语句将停止代码,但如果我没有它,它将使应用程序崩溃,因为它只会不断地写入列表框。
如何运行代码
while (checkBox1.Checked)
每 X 秒?
【问题讨论】:
-
使用
Thread.Sleep或更好地使用System.Timers类
标签: c# timer while-loop wait