Question

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

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.

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top