C#程序冻结在for循环中 [英] C# Program freezes in for loop

查看:79
本文介绍了C#程序冻结在for循环中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有这段代码,可以启动一个过程,等待8秒钟,然​​后再次杀死它.

I have this code here that starts a process wait 8 seconds and then kill it and again.

for (int i = 0; i < 20; i++)
{
    Process pro = new Process();
    pro.StartInfo.FileName = @"C:\Program Files (x86)\Mozilla Firefox\firefox.exe";
    pro.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
    pro.Start();

    Thread.Sleep(8000);

    try
    {
        pro.Kill();
        Thread.Sleep(1000);
    }
    catch
    {
        return;
    }
}

当我在调试模式下或直接从.exe运行应用程序时,它成功启动并终止了该进程,但已冻结.我无法移动其窗口或单击其他按钮.

As i run the application either on debug mode or direct from the .exe , it successfully starts and kills the process but it is frozen. I cant move its window around or click on other buttons..

推荐答案

它被冻结了.我无法移动其窗口或单击其他按钮.

it is frozen. I cant move its window around or click on other buttons.

是正确的.您说要让线程进入睡眠状态.

That's correct. You said to put the thread to sleep.

人们似乎有一个奇怪的想法,即按下按钮时运行代码是由魔术产生的.魔术不会发生这种情况.发生这种情况是因为线程运行的代码处理了操作系统中的单击按钮"消息.如果您将线程置于睡眠状态,则它将停止处理这些消息,因为它处于睡眠状态.

People seem to have this strange idea that running code when buttons are pressed happens by magic. It does not happen by magic. It happens because the thread runs code that processes the "a button was clicked" message from the operating system. If you put a thread to sleep then it stops processing those messages, because it is asleep.

将线程置于睡眠状态是99%的时间要做的完全错误的事情,所以请不要这样做.

Putting a thread to sleep is 99% of the time the completely wrong thing to do, so just don't do it.

在C#5中要做的正确的事情是将您的方法设为async,然后执行await Task.Delay(whatever).或者,创建一个计时器,在几秒钟后计时.在滴答处理事件中,请关闭计时器并在那里执行逻辑.

The right thing to do in C# 5 is to make your method async and then do an await Task.Delay(whatever). Alternatively, create a timer that ticks after some number of seconds. In the tick handling event, turn the timer off and do your logic there.

这篇关于C#程序冻结在for循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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