表单在 while 循环期间冻结 [英] Form freezes during while loop

查看:25
本文介绍了表单在 while 循环期间冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码可以检查某个应用程序是否正在运行

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.

推荐答案

在这种情况下,您实际上希望在与主 UI 线程分离的线程上完成一些工作.

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

理想的情况是利用 BackgroundWorker 对象,它会很高兴地在另一个线程上运行并且不会阻塞您的 UI.

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);

这将创建 BackgroundWorker 并将其 DoWork 事件绑定到我们将要创建的 workerDoWork 处理程序:

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);
    }
 }

现在开始工作:

 worker.RunWorkerAsync();

查看本教程:http://www.codeproject.com/Articles/99143/BackgroundWorker-Class-Sample-for-Beginners

这篇关于表单在 while 循环期间冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆