-3

I have the following problem with System.Windows.Forms (C#):

I have a CheckBox in my program and I defined an event handler for CheckedChanged. The problem is that when the user clicks the CheckBox, it may happen that it takes several seconds until the CheckBox is visibly marked as checked.

I set a breakpoint inside the CheckedChanged event and noticed that indeed, it sometimes takes several seconds until the CheckedChanged event fires. How can it be that the CheckedChanged event lags behind that much?

Unfortunately I have not been able to find information in the literature regarding the matter when exactly the CheckedChanged event is triggered. Might it be that another event is handled first before the CheckedChanged event is triggered, so I could catch this event instead and make the check-arrow appear in time?

Thank you for your help and suggestions.

Lars Kristensen
  • 1,410
  • 19
  • 29
Entwickler582
  • 73
  • 1
  • 7
  • normally you see that when you do processing on the UI thread. use debug.WriteLine to dump out call notes to your various handlers so you can see without having to step through your code what happens between click and result – BugFinder Apr 17 '18 at 07:11
  • So, if you make an empty form with only a checkbox and only its event handler do you experience the same lag? – Steve Apr 17 '18 at 07:14
  • The problem does not appear with forms in general, it is specific to this form, and not even with this form it occurs always. My experiments have yielded that the CheckedChanged event is triggered before the Click and the CheckedStateChanged events. It seems that the CheckedChanged event is indeed triggered right after the change occurs. The question is just why it takes so many seconds after the click? What could be the cause of this? – Entwickler582 Apr 17 '18 at 07:26
  • 1
    @Entwickler582 - You need to provide a [mcve]. – Enigmativity Apr 17 '18 at 10:06
  • @Entwickler582 Did you find a solution for this issue? – Lars Kristensen May 09 '18 at 13:17

1 Answers1

1

The CheckedChanged event occurs when the Checked property of the CheckBox changes.

The UI will not update the checkmark inside the checkbox, until after any eventhandler for this event has been handled. If you are doing a lot of processing in the handler for the CheckedChanged event, then it will take some time before the checkmark is added/removed from the checkbox.

If you need the UI to update quickly, then consider doing the processing in a separate thread. This can be done pretty easily, using Task.

Here's a quick example:

private void MyCheckBox_CheckedChanged(object sender, EventArgs e)
{
    //Don't do this:
    //ThreeSecondMethod();

    //Instead, do this:
    Task.Run(() => ThreeSecondMethod());
}

private void ThreeSecondMethod()
{
    DateTime deadline = DateTime.Now.AddSeconds(3);

    while(DateTime.Now < deadline)
    {
        /* Do nothing */
    }

    MessageBox.Show("Done!");
}
Lars Kristensen
  • 1,410
  • 19
  • 29