-3

I'm trying to do something very simple like below.

UpdateUI()
{
   DisableButtons()
   LongRunningOperation_UpdateLotsOfInformation()
   EnableButtons()
}

When I do a UI update, I want to disable the buttons while the UI is loading. However, when I run this code the message for DisableButtons() doesn't seem to be processed until all of UpdateUI() completes. The effect is that the buttons remain enabled for the duration of loading (may be 1 minute) then when the long running loading completes the buttons quickly flicker from enabled to disabled.

How do I make sure the buttons are disabled before processing the long running operation?

Any help would be greatly appreciated, thank you.

Kurt Madland
  • 45
  • 1
  • 6
  • 5
    Background worker, Thread pool, async/await, Tasks... – Uwe Keim Apr 07 '20 at 19:26
  • Your question isn't specific about which of the several GUI APIs you're using. Winforms and WPF are a couple of the most commonly used, so see marked duplicates for just a handful of the _many_ already-answered questions on Stack Overflow that address your question. – Peter Duniho Apr 07 '20 at 20:09

1 Answers1

0

How do I make sure the buttons are disabled before processing the long running operation?

  • Invoke back into the UI thread, which will redraw all pending operations

or better

  • Why the heck do you do long running operations on the UI Thread to start with? Look up threading and start them on another thread.

or also:

  • You talk about loading. if all the loading happens in async methods, the problem should not be there, IIRC, to start with.
TomTom
  • 61,059
  • 10
  • 88
  • 148
  • Thank you for the quick response. When you say "Invoke back into the UI thread, which will redraw all pending operations" can you elaborate? I haven't done any "Invoke" stuff and am not sure what you mean. – Kurt Madland Apr 07 '20 at 19:31
  • In WinForms, you should be able to use `async` and `await`, either natively (if your long running work is naturally async), or by awaiting a `Task.Run` call to do the work on a second thread. If your long running work is going to be updating the UI during its efforts, then you are either going to need to `Invoke` back to the UI thread to do that or refactor things into multiple awaitable chunks. Look up `Control.Invoke` and `.InvokeRequired`. Sorry, I thought this was WinForms-specific. The same comments work for WPF – Flydog57 Apr 07 '20 at 22:41