Mallory Rich Mallory Rich - 1 month ago 13
C# Question

Using a checkbox to loop

I'm creating a program where data is being filled into a listbox. When I click a checkbox to loop, it should loop from the very beginning. When I click the checkbox it does not check and it also prevents me from clicking anything else because of the infinite loop. Does anyone know a solution around this?

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
while(checkBox1.Checked == true)
{
Play();
}
}

Answer

You either need Play to execute on a background thread or you need to pulse the windows message pump so give the UI time to react to input. This is the latter:

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
    while(checkBox1.Checked == true)
    {
        Play();
        Application.DoEvents();
    }
}

DoEvents causes windows to process any messages (like UI input) that are currently in the message queue. Without it, windows messages are never processed because Play is on the UI thread and the message pump never has a chance to run, so even if you are furiously clicking on the checkbox, windows never has a chance to tell your app about it.

There are a lot of ways to do this with Play on a background thread. Those examples are a little bit more involved than the message pump approach of DoEvents.

Bare in mind that multi-threading is more of an advanced approach that can be harder to implement correctly, though is something worth understanding.

Comments