Amrmsmb
Amrmsmb

Reputation: 11406

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

Upvotes: 1

Views: 99

Answers (2)

Rob
Rob

Reputation: 437917

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?

Upvotes: 2

CRD
CRD

Reputation: 53010

On the assumption that "main" means the main() startup function and the code you show is the whole body of main() then:

As soon as main() returns the app is terminated. So in your case block1 may or may not start executing but the app quickly terminates regardless.

Copy your lines into the applicationDidFinishLaunching: (macOS) or application:didFinishLaunchingWithOptions: (iOS) methods of a standard GUI app and then run that. A GUI app as a run loop which keeps it running until some event terminates the app so your app will run long enough for your block1 to execute (you might want to change the 700 to say 7 for the test or you'll be waiting a long time for it to finish).

HTH

Upvotes: 1

Related Questions