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

查看:66
本文介绍了表单在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天全站免登陆