Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form freezes during while loop

I have a piece of code that checks if a certain application is running

while (Process.GetProcessesByName("notepad").Length == 0)
{
     System.Threading.Thread.Sleep(1000);
}

It will check if the user is running notepad but it makes the form freeze and stop responding after a few seconds. I don't know if there is a better solution to fix this problem.

like image 483
Kevin Coenegrachts Avatar asked Dec 28 '13 15:12

Kevin Coenegrachts


1 Answers

In this case, you actually want some work done on a thread that's separate from your main UI thread.

The ideal scenario would be to leverage the BackgroundWorker object, which will happily run on another thread and not block your UI.

I won't give you a full explanation, as there are plenty of tutorials out there, but you're going to want to do something like:

var worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);

This creates the BackgroundWorker and binds its DoWork event to the workerDoWork handler we are about to create:

 void worker_DoWork(object sender, DoWorkEventArgs e)
 {
    //Glorious time-consuming code that no longer blocks!
    while (Process.GetProcessesByName("notepad").Length == 0)
    {
        System.Threading.Thread.Sleep(1000);
    }
 }

Now start the worker:

 worker.RunWorkerAsync();

Check out this tutorial: http://www.codeproject.com/Articles/99143/BackgroundWorker-Class-Sample-for-Beginners

like image 146
Mister Epic Avatar answered Nov 15 '22 02:11

Mister Epic