Why won’t control update/refresh mid-process

If you’re doing your processing on the UI thread, it won’t be able to do anything else (like redraw updated labels) while the processing is running. So for instance, if the processing is happening because the user clicked a button and is triggered by the button click handler (without explicitly placing it on another thread), it’s running on the UI thread. Even though you update the label’s text, it doesn’t get drawn until it receives a paint message, at which point it’s probably busy doing your processing.

The answer is to do long-running processing on a separate thread. The hack (IMHO) is to use Application.DoEvents to let the UI thread do some UI stuff during your processing. If you put one of those after updating the label and before you start your processing, odds are pretty high the label will get repainted. But then, during the processing, no further paint events can get processed (leading to half-drawn windows when someone moves another app window over your app and back, etc.). Hence my calling it a hack (even though, er, um, I’ve been known to do it 🙂 ).

Edit Update based on your edits:

Re

So I guess the “processing” is taking place on the UI thread but eventhandler is invoked on it’s own thread…

I’m assuming DoSomeProcess is triggered from the UI thread (e.g., in direct response to a button click or similar). If so, then yes, your processing is definitely on the UI thread. Because TriggerProcessStarted triggers your callback asynchronously via BeginInvoke, you have no idea when it will run, but in any case your code then immediately launches into processing, never yielding, so no one else is going to be able to grab that thread. Since that’s the UI thread, the call to the delegate will block on the Invoke call setting the label’s text, whereupon it has to wait for the UI thread (which is busy processing). (And that’s assuming it’s scheduled on a different thread; I couldn’t 100% convince myself either way, because Microsoft has two different BeginInvokes — which IIRC one of the designers has acknowledged was a Really Dumb Idea — and it’s been a while since I fought with this stuff.)

If you make the TriggerProcessStarted calls to your callbacks synchronous, you should be okay. But ideally, schedule the processing (if it’s not doing UI) on its own thread instead.

Leave a Comment