iOS GCD之dispatch_after

GCD is a function of a delay in the implementation of, he has two parameters, the first parameter is dispatch_time_t that is how long the delay, the second parameter is dispatch_queue_t which is added in the queue

dispatch_after(dispatch_time_t when, dispatch_queue_t queue,
        dispatch_block_t block);

dispatch_after add delay to perform tasks in a block in the queue, the queue to wait for the task of executing the block will be implemented, if the thread is blocked, the time delay of the execution is not identified, you may not be set duration.

E.g:

    NSLog(@"第一步");
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"我是延迟执行的函数 ---%@",[NSThread currentThread]);
    });
    
    NSLog(@"耗时任务开始");
    NSInteger count = 0;
    for (long long i = 0; i < 5000000000; i++)
    {
        count ++;
    }
    NSLog(@"耗时任务结束");
6206716-a063b80ae3343598.png
Screenshot 7.19.46.png 2019-06-01 PM

We can see by the results, print within dispatch_after function block is executed only after 12 seconds is not what we set five seconds, this is because the second argument dispatch_after function of the main thread is passed, the delay task Add in the main thread, the main thread and print a time-consuming task, to wait until they have finished the time-consuming task to perform the execution block dispatch_after.

Below we will dispatch_after second parameter function into another queue

    dispatch_queue_t queue = dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT);
    NSLog(@"第一步");
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), queue, ^{
        NSLog(@"我是延迟执行的函数 ---%@",[NSThread currentThread]);
    });
    
    NSLog(@"耗时任务开始");
    NSInteger count = 0;
    for (long long i = 0; i < 5000000000; i++)
    {
        count ++;
    }
    NSLog(@"耗时任务结束");
6206716-45af52d690461dbd.png
Screenshot 7.31.47.png 2019-06-01 PM

We found that we really are in accordance with the implementation of the set of five seconds

Guess you like

Origin blog.csdn.net/weixin_33836874/article/details/90918168
ios