Search code examples
iosobjective-cgrand-central-dispatch

What is the best way to ensure the main thread is blocked while a background thread is processing?


Consider the following case:

Main Thread -----UIView info \ --------------------------------------- / Button Updated ------
                              \ (Some Event)                          / (Some Event)
                               \                                     /
BG Thread ---------------------Validate UIView info-----Update Button------------------------
  1. On the main thread, a UIView is present
  2. UIView makes a dispatch call is made to a background thread
  3. In the BG Thread, the UIView's info is validated.
  4. BG Thread makes a dispatch call to a UIButton on the main thread to update it.

My question is - notice how there is a gap between UIView info and the UIButton which means that the app could technically be updated during this time. How can I possible stop this gap? Essentially, from the BG thread, block the Main Thread till the call comes back?


Solution

  • You cannot and must never block the main thread. If you do, the interface will freeze and, if the blockage lasts too long, the WatchDog process will kill your app dead before the user's very eyes.

    You can give the user a sense that something is going on, and discourage the user from doing anything, by, say, turning off user interaction and putting up a spinner. But in general, yes, multithreading is hard; you must be prepared for the possibility that you will come back onto the main thread when the app has changed state.