0

我有一个轮询计时器来检查进程是否正在运行。我有以下简单的代码:

bool alreadyChecked = false; //check if the wait to check the second time is already over

**Timer_elapsed event**

Process sampleProcess[] = Process.GetProcessesByName("notepad");
if(sampleProcess.length > 0)
{
//Process is running
return;
}
else
{
//Process is not running, so do the following

//Wait for some time and check again (set alreadyChecked = true when the wait is over)
if (alreadyChecked){
//Run the process}
else{
//The process has started running while we were waiting
return;}
    }

我无法waiting code在事件内部实现,因此它可以等待然后再次触发事件。(即使我们实现了等待时间,Timer_elapsed 事件也会在我们等待时再次被定时器触发。)

有什么建议么?

4

1 回答 1

0

您应该创建一个单独的线程并使用 sleep 方法,使用 BackgroundWorker 是最好的选择。您还可以使用计时器线程。

**BackgroundWorker_DoWork event**
int nTrials = 0; // this method will help you pick any number of trials before launching the applicaion
bool isRunning = false;
while((isRunning = Process.GetProcessesByName("notepad") == 0)  || nTrials < 2)
{
    Thread.Sleep(1000); // w8 1 second before queriying the process name
    nTrials++;
} 

if ( isRunning ) RunProcess();

不要在你的主线程上使用 sleep 方法,否则你的应用程序将停止处理睡眠时间的消息。

于 2012-05-29T05:07:52.663 回答