-1

I'm trying to have serial data sent out continuously while a check button is being pressed in Visual Studio. So far, this is what I've come up with:

private void checkBox1_CheckedChanged_1(object sender, EventArgs e)
    {
        while (checkBox1.Checked)
        {
            serialPort1.Write("D");
            Task.Delay(100);
            if (checkBox1.Checked != true)
            {
                break;
            }
        }                                            `    

For some reason, whenever I launch the program and check the box, the program freezes. I can't exit the program or minimize it or anything. It just stops in its tracks.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • 3
    The issue is you are blocking the UI thread in a endless loop, it cant process the UI. – TheGeneral Sep 09 '18 at 01:03
  • You are in an event handler for the checkbox when it changes state, once. The state cannot change in your loop. And the loop ties up the UI thread. So, results = expected. – JamieMeyer Sep 09 '18 at 01:04
  • Also a checkbox changed event is not really the most appropriate place to start a long running task – TheGeneral Sep 09 '18 at 01:06
  • How could I make it so that it could change state more than once? – Owen Thornton Sep 09 '18 at 01:06
  • Possible duplicate of [WinForm Application UI Hangs during Long-Running Operation](https://stackoverflow.com/questions/1216791/winform-application-ui-hangs-during-long-running-operation) – Ian Sep 09 '18 at 01:11
  • Task.Delay(100); does not await, it continues immidiately (blocking the UI thread). You should make the eventhandler async and await Task.Deley(100); – Poul Bak Sep 09 '18 at 02:15

2 Answers2

2

The user interface in Windows is based on messages. Your while loop runs in the thread where those messages would be handled. While your code runs, no messages are handled. The user interface cannot be redrawn and cannot react to user input.

Better approach: Use a Timer component. The Tick event of the Timer will be executed every n milliseconds according to the Interval property of the Timer. In the Tick event, you can check the Checkbox state and then do something or not depending on whether the checkbox is checked.

This is a good approach if "do something" is a very short activity. For longer activities, you nee a bit more complex setup that is beyond the scope of a SO question unless you provide more details.

NineBerry
  • 26,306
  • 3
  • 62
  • 93
1

You're blocking the UI thread because your event is being handled synchronously. Refer to this answer for some tips on async/await programming: How do I update the GUI from another thread?

brandon-barnett
  • 1,035
  • 9
  • 13