问题
I have the method in which I need to make a 5 sec delay every time I call it. Firstly I make it with sleep(5);
- it worked excellent but I believe - it's not obj-c way, so I tried to write it with GCD help. The first call of this procedure make a delay about 5 sec, but other calls in this queue are going one after one without delay. How to solve this problem?
- (void) buyItemAtUUID:(NSString*)UUID
{
dispatch_barrier_async(dataManagerQueue, ^{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
double delayInSeconds = 5.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dataManagerQueue, ^(void){
NSInteger path = [self indexFromObjectUUID:UUID];
if (path != NSNotFound)
{
NSMutableDictionary *item = [[_items objectAtIndex:path] mutableCopy];
NSNumber *value = [NSNumber numberWithFloat:[[item objectForKey:@"Quantity"] floatValue] - 1.0];
}
});
});
}
回答1:
The first call of this procedure make a delay about 5 sec, but other calls in this queue are going one after one without delay.
That's usually desired behavior. The reason you shouldn't call sleep()
is that it'll block the thread, preventing anything else in that thread from happening. If you block the main thread, your device will appear to freeze, which isn't a very nice user experience.
GCD provides a nice dispatch_group_wait()
function that lets you make one set of tasks wait for some other group to finish. Take a look at Waiting on Groups of Queued Tasks for an example.
回答2:
dispatch_barrier_async
only stops blocks added to the concurrent queue after this block from running. The blocks that were already queued are not prevented from running.
来源:https://stackoverflow.com/questions/18715366/delay-via-gcd-vs-sleep