在timer_elapsed事件中实现等待例程

时间:2012-05-29 04:59:26

标签: c#

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

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事件也会在我们等待的时候再次被定时器触发。)

有什么建议吗?

1 个答案:

答案 0 :(得分: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方法,否则应用程序将停止处理休眠时间的消息。