C#程序使用秒表冻结以对动作计时 [英] C# program freezes using stopwatch to time an action

查看:122
本文介绍了C#程序使用秒表冻结以对动作计时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制灯光的Windows窗体程序。这种灯有其自己的类别。我可以做一些事情,例如将其关闭然后更改颜色等。这可以毫无问题地进行。但是,我想做的是使灯点亮特定的时间,即100毫秒或300毫秒(取决于使用情况)。

I have a Windows form program which controls a light. This light has its own class. I can do things like turn it on an off and change the color etc. This I can do without issue. What I want to be able to do, however, is make the light go on for a specific amount of time, i.e. 100 milliseconds or 300 milliseconds (depending on use).

我尝试使用秒表来执行此操作,但是当我单击要执行此操作的按钮时,它将冻结程序。指示灯亮起,然后没有熄灭,并且我不能使用要关闭的停止按钮。

I have tried to used stopwatch to do this, but when I click on the button that is meant to do this, it freezes the program. The light goes on, then doesn't turn off, and I can't use the stop button I have which is meant to turn it off.

程序会加载指示灯,并对其进行初始化,并显示一条警报,指出已完成并检测到一个指示灯。然后我用这个:

The program loads the light, and initialises it, and displays an alert saying it has done this and detected one light. Then I use this:

   private void Red_Click_1(object sender, EventArgs e)
    {
        //Displays Red

        System.Threading.Tasks.Task.Factory.StartNew((Action)delegate()
        {
            displayRedDot();
        });
     }

这是displayRedDot()

This is the displayRedDot()

public void displayRedDot()
    {

        System.Diagnostics.Stopwatch clock1 = new System.Diagnostics.Stopwatch();
        long elapsedTime = clock1.ElapsedMilliseconds;
        clock1.Start();
        while (elapsedTime < 100)
        {
            oBlynclightController.Display(BlynclightController.Color.Red);
        }
        oBlynclightController.Display(BlynclightController.Color.Off);
        clock1.Stop();


    }

我还有其他一些功能,与此相同,但时间不同,我还未在任何地方调用它,因为我无法使它正常工作。

I have some other functions, which are identical this with a different time, which I haven't invoked anywhere yet because I can't get this to work.

推荐答案

您的代码将永远无法正常工作,因为您正忙于等待来阻塞UI线程。这是您的程序似乎死机的原因。改用计时器或异步/等待

Your code will never work since you are blocking the UI thread by busy waiting. This is the reason for your program seems to freeze. Use a timer or async/await instead

async  void DisplayRedDot(int duration)
{
    oBlynclightController.Display(BlynclightController.Color.Red);
    await Task.Delay(duration);
    oBlynclightController.Display(BlynclightController.Color.Off);
}

这篇关于C#程序使用秒表冻结以对动作计时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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