通过GCD延迟与sleep() [英] Delay via GCD vs. sleep()

查看:173
本文介绍了通过GCD延迟与sleep()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种方法,每次调用它都需要延迟5秒.首先,我用sleep(5);做到了这一点-效果很好,但我相信-这不是obj-c方式,因此我尝试在GCD帮助下编写它.此过程的第一次调用会延迟约5秒钟,但是此队列中的其他调用将一个接一个地进行而没有延迟.如何解决这个问题?

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];
             }
        });
    });
}

推荐答案

此过程的第一次调用会延迟约5秒钟,但其他 此队列中的呼叫将一拖一地接连进行.

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.

通常是期望的行为.您不应该调用sleep()的原因是它将阻塞线程,从而防止该线程中的任何其他事件发生.如果您阻塞主线程,您的设备将显示为死机,这不是很好的用户体验.

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提供了很好的dispatch_group_wait()功能,可让您执行一组任务以等待其他组完成.看看 等待排队的任务组 .

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.

这篇关于通过GCD延迟与sleep()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆