title: How to dispatch on main queue synchronously without a deadlock?
body: <p>I need to dispatch a block on the main queue, synchronously. I don’t know if I’m currently running on the main thread or no. The naive solution looks like this:</p>
  
  <pre><code>dispatch_sync(dispatch_get_main_queue(), block);
  </code></pre>
  
  <p>But if I’m currently inside of a block running on the main queue, this call creates a deadlock. (The synchronous dispatch waits for the block to finish, but the block does not even start running, since we are waiting for the current one to finish.)</p>
  
  <p>The obvious next step is to check for the current queue:</p>
  
  <pre><code>if (dispatch_get_current_queue() == dispatch_get_main_queue()) {
      block();
  } else {
      dispatch_sync(dispatch_get_main_queue(), block);
  }
  </code></pre>
  
  <p>This works, but it’s ugly. Before I at least hide it behind some custom function, isn’t there a better solution for this problem? I stress that I can’t afford to dispatch the block asynchronously – the app is in a situation where the asynchronously dispatched block would get executed “too late”.</p>