Form freezes during while loop

纵饮孤独 提交于 2019-12-21 03:00:51

问题


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.


回答1:


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




回答2:


The form freezes because your code is running on the UI/Main thread.
So because you are Sleeping the thread while notepad is not open then your form will lock up.
If you run your code asynchronously then you move the worker thread away from the UI.
See here for an C# async overview




回答3:


You could always just start an asynchronous task to keep updating the UI

Task f = Task.Factory.StartNew(() =>
        {
            while (true)
            {
                //This would make the form become responsive every 500 ms
                Thread.Sleep(500); //Makes the async thread sleep for 500 ms
                Application.DoEvents(); //Updates the Form's UI
            }
        });

Or this to run it on a different thread

Task f = Task.Factory.StartNew(() =>
{
while (Process.GetProcessesByName("notepad").Length == 0)
    {
        System.Threading.Thread.Sleep(1000); //Does the while loop every 1000 ms
    }
});


来源:https://stackoverflow.com/questions/20816153/form-freezes-during-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!