Search code examples
iosobjective-cgrand-central-dispatchdispatch

How to get the dispatch_async running


In the below code, on running the app, the log inside the block variable

block1

Is never got executed, only the

NSLog(@"Delay_Expired");

Please let me know how to get the dispatch_async running.

main

dispatch_block_t block1 = ^{
    for (int i = 0; i < 10; i++) {
        [NSThread sleepForTimeInterval: 700];
        NSLog(@"current i = %d", i);
    }
};
dispatch_queue_t defaultPriority = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_queue_t backgroundPriority = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
NSLog(@"Delay_Expired");

dispatch_async(defaultPriority, block1);

Solution

  • It is running, but it’s running asynchronously, and you are simply exiting your app before it has a chance to finish. If you try this in a GUI app that stays alive until the user manually quits, you’ll see it behave like you expected.

    If you’re doing this in a command line app, you can use dispatch groups to wait for the dispatched code to finish, e.g.:

    dispatch_group_t group = dispatch_group_create();
    
    dispatch_queue_t defaultPriority = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_group_async(group, defaultPriority, ^{
        for (int i = 0; i < 10; i++) {
            [NSThread sleepForTimeInterval:0.7];
            NSLog(@"current i = %d", i);
        }
    });
    
    NSLog(@"Waiting");
    
    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
    
    NSLog(@"All done");
    

    You don’t generally do this in most GUI apps, but if you really want your command line app to wait for the dispatched code to finish, this will do the job.


    By the way, are you aware that sleepForTimeInterval uses seconds, not milliseconds? Perhaps you intended to use 0.7 seconds, not 700 seconds?