tags:

views:

49

answers:

1

I have a winform with some buttons that are updated in an event handler. The event is fired from a background thread, then the appearance is set via the Invoke method. The buttons will just get enabled or disabled. Something will happen at unpredicable times, though:

  • The button will not change appearance visually. When it should be enabled, it still looks like it's disabled
  • Clicking on the "disabled" button still fires the click event - as if its actually enabled underneath
  • After resizing or moving the form, the component's appearance is set correctly to enabled.
  • Only the components that are updated in this manner are affected. Other components on the form look/behave fine.

Here is how the button is getting updated in code:

public class Form1 :Form
{
     void eventFromThread(object sender, CustomEventArgs e)
     {
           if(e.enable)   RunOnUiThread(ShowEnabledView);
           else RunOnUiThread(ShowDisabledView);
     }

     void ShowEnabledView()
     {
          button1.Enabled = true;
     }

     void ShowDisabledView()
     {
          button1.Enabled = false;
     }

     void RunOnUiThread(MethodInvoker method)
     {
          try
          {
                if(InvokeRequired)
                {
                     Invoke(method); 
                }
                else
                     method.Invoke();
           }
           catch(ObjectDisposedException)
           { return;}
           catch(InvalidOperationException)
            {return;}
     }
}

I have tried forcing a refresh on the button, and it hasn't re-occurred yet, but its only been a couple of days. The issue just seems to pop up when it wants to, so I can't really be sure I'm fixing anything. Can anyone shed any light on this?

+2  A: 

try calling

System.Windows.Forms.Application.DoEvents()

after you change the button's Enabled property

Steven A. Lowe
How does DoEvents help? If the button is enabled ok, shouldn't be repainted at that time?
R.B.
@[R.B.]: ideally yes it should, but DoEvents forces the GUI thread to process immediately. The symptoms you describe hint that the GUI thread processing is being delayed. Did you try it?
Steven A. Lowe
I've added DoEvents, hopefully it will scare the problem away. Is it possible that GUI processing was delayed several days? I've seen this happen where the UI should have updated the components on a Friday, the program was unattended over the weekend, and on Monday the buttons were still visually disabled.
R.B.
@[R.B.]: yes, if the background threads were eating the CPU - of course with MS Windows, anything is possible ;-)
Steven A. Lowe
Over a week w/o incident. Thanks, Steven.
R.B.
@[R.B.]: you're welcome, I'm glad it helped!
Steven A. Lowe