Simple helpers for dispatch_async / by Brian Lambert

Below are a couple of simple helpers I wrote that make working with Apple's Grand Central Dispatch easier on the eyes.

The first method is called OnMainThread. It executes a block on the main thread. Additionally, it detects whether it was called on the main thread, and simply executes the block, if it was.

// Executes the specified block on the main thread.
static inline void OnMainThread(dispatch_block_t block)
{
    // If this is the main thread, then just execute the block; otherwise,
    // dispatch the block.
    if ([NSThread isMainThread])
    {
        block();
    }
    else
    {
        dispatch_async(dispatch_get_main_queue(),
                       block);
    }
}

The second method is called OffMainThread. It executes a block off the main thread. Additionally, it detects whether it was called off the main thread, and simply executes the block, if it was.

// Executes the specified block off the main thread.
static inline void OffMainThread(dispatch_block_t block)
{
    // If this isn't the main thread, then execute the block; otherwise,
    // dispatch the block.
    if (![NSThread isMainThread])
    {
        block();
    }
    else
    {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
                                                 0),
                       block);
    }
}

Here's an example of how these helpers can be used together. Off the main thread, this example performs a complex calculation and formats the result of the computation for display. Next, on the main thread, it updates the UI.

OffMainThread(^{
    double bigNumber = [self computeBigNumber];
    NSString * bigNumberText = [NSString stringWithFormat:@"%.2f", bigNumber];
    
    OnMainThread(^{
        [[self labelBigNumbersetText:bigNumberText];
    });
});