C# program freezes using stopwatch to time an action

前端 未结 2 1809
时光取名叫无心
时光取名叫无心 2021-01-24 08:58

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.

相关标签:
2条回答
  • 2021-01-24 09:09

    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);
    }
    
    0 讨论(0)
  • 2021-01-24 09:32

    elapsedTime will never change its value. You initialize it right after creating the stopwatch, but never assign a new value to it. Stopwatch.ElapsedMilliseconds is a long. long is a value type. A copy is created and assigned to elapsedTime. You need:

    while (clock1.ElapsedMilliseconds < 100)
    {
        oBlynclightController.Display(BlynclightController.Color.Red);
    }
    

    Note that this loop is going to run very quickly until that check returns false. Is this really what you want? I don't know exactly what your code is doing (you don't show us), but why not just set the color to red, wait 100ms, and then set it to... erm, Off.

    It's also difficult for humans to pick up a change that only lasts 100ms. It's going to be a flicker at best.

    0 讨论(0)
提交回复
热议问题