Dispatching your work

2 Nov

Grand Central Dispatch is an awesome technology. There is a ton of stuff in GCD we could talk about, but I’m going to pick one specific part to talk about today.

Dispatch Groups. Apple defines dispatch groups as “a way to monitor a set of block objects for completion. (You can monitor the blocks synchronously or asynchronously depending on your needs.) Groups provide a useful synchronization mechanism for code that depends on the completion of other tasks.”

But what does that really mean to you? Well say for example you want to run some tasks on a background thread and then execute some code when all the background tasks have finished. You could try and use flags to track the state of all the tasks or maybe setup a counter system to track their status and then execute your completion code when all the tasks have finished. But wait, smell that? That’s code smell. You know there’s a better way, and your right. Your so smart.

Dispatch groups provide a convenient way of tracking tasks and can notify you when the tasks have been completed. A dispatch group keeps a counter of active tasks and when the count drops to zero it can call a designated block.

Heres a quick example.

// Create a dispatch group
dispatch_group_t group = dispatch_group_create();

// cycle through dispatching some background tasks
for(int i = 0; i < 10; i++)
{
	// increment the group's task counter
	dispatch_group_enter(group);
	
	// start a background task
	yourPerformAsyncBlock(^{
		// do some work on a background thread
		
		// decrement the group's task counter
		dispatch_group_leave(group);
	});
}

// set a block for the dispatch group to call when the group's counter gets to zero
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
	// all our tasks have finished
	UpdateUI();
});