如何获得 dispatch_async 运行

How to get the dispatch_async running

在下面的代码中,在 运行 应用程序上,块变量

内的日志
block1

从来没有被执行过,只有

NSLog(@"Delay_Expired");

请告诉我如何获得 dispatch_async 运行。

主要

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

假设“main”表示main()启动函数并且您显示的代码是main()的整个主体,那么:

一旦 main() returns 应用程序终止。因此,在您的情况下,block1 可能会或可能不会开始执行,但无论如何应用程序都会迅速终止。

将您的行复制到标准 GUI 应用程序的 applicationDidFinishLaunching: (macOS) 或 application:didFinishLaunchingWithOptions: (iOS) 方法中,然后 运行 那个。一个 GUI 应用程序作为一个 运行 循环,它保持 运行ning 直到某些事件终止应用程序,这样你的应用程序将 运行 足够长的时间让你的 block1 执行(你可能想要将 700 更改为 7 进行测试,否则您将等待很长时间才能完成)。

HTH

它是 运行,但它是 运行 异步的,您只是在它有机会完成之前退出您的应用程序。如果您在 GUI 应用程序中尝试此操作,该应用程序在用户手动退出之前一直保持活动状态,您会看到它的行为与您预期的一样。

如果您在命令行应用程序中执行此操作,则可以使用调度组来等待调度代码完成,例如:

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

您通常不会在大多数 GUI 应用程序中执行此操作,但如果您真的希望命令行应用程序等待分派的代码完成,这将完成这项工作。


顺便问一下,您知道 sleepForTimeInterval 使用秒而不是毫秒吗?也许您打算使用 0.7 秒,而不是 700 秒?