dubbeat dubbeat - 2 years ago 325
iOS Question


Can somebody please provide me with an example of when you would use DISPATCH_TIME_NOW vs DISPATCH_TIME_FOREVER when using semaphores?

What is the difference between the 2 and in what case would I use one over the other?

According to the docs DISPATCH_TIME_NOW means timeout immediately. DISPATCH_TIME_FOREVER means timeout infinity.

Why would you ever want the former, ie: timeout immediately.

Answer Source

You can timeout immediately to check if an block has finished computing. Similarly you can wait forever until a block has completed before continuing executing another block.

An example of checking if a group is finished could look like this.

if (dispatch_group_wait(myDispatchGroup, DISPATCH_TIME_NOW) == 0) {
    // myDispatchGroup is finished... 
} else {
    // myDispatchGroup is _not_ finished...

Checking if a group is finished when waiting forever doesn't make sense since the function is going to wait forever. Instead we use the function to synchronously block (block as in pause or wait, not as in GCD block) until the group is completed.

// Enqueue myDispatchGroup

// Wait for it to finish
dispatch_group_wait(myDispatchGroup, DISPATCH_TIME_FOREVER); 

// Do other work that depends on myDispatchGroup being completed
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download