为什么Dispatch_group_notify在不同环境中的工作方式不同?

时间:2018-01-11 07:46:24

标签: ios xcode grand-central-dispatch

第一种情况是我创建了一个命令行工具应用程序,并运行此代码。

    NSLog(@"Main:%@", [NSThread currentThread]);

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();

    dispatch_group_async(group, queue, ^{
        NSLog(@"Task1:%@", [NSThread currentThread]);
    });

    dispatch_group_async(group, queue, ^{
        NSLog(@"Task2:%@", [NSThread currentThread]);
    });

    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"Finish:%@", [NSThread currentThread]);
    });

登录终端

    Main:<NSThread: 0x1028033b0>{number = 1, name = main}
    Task2:<NSThread: 0x10040f0f0>{number = 2, name = (null)}
    Task1:<NSThread: 0x1006008d0>{number = 3, name = (null)}

如果我想在queue显示上次登录并替换main queue

     dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"Finish:%@", [NSThread currentThread]);
    });

queue

     dispatch_group_notify(group, queue, ^{
        NSLog(@"Finish:%@", [NSThread currentThread]);
    });

终端打印最后一个日志。但是为什么它不能在主队列中撤销?

当我将此代码复制到简单的iOS Application.All效果很好:

Main:<NSThread: 0x600000070ac0>{number = 1, name = main}
Task2:<NSThread: 0x6000002633c0>{number = 3, name = (null)}
Task1:<NSThread: 0x600000263480>{number = 4, name = (null)}
MainFinish:<NSThread: 0x600000070ac0>{number = 1, name = main}

我尝试将sleep(1)添加到“命令工具栏”中的“任务1”,但它似乎阻止了队列并且只打印日志:Task2 ....但这一切都很简单iOS应用程序。

为什么导致这些不同?

1 个答案:

答案 0 :(得分:1)

image here

与其他活动创建的队列不同,您应该调用dispatch_main()方法来执行提交给主线程的块

image here

相同代码在iOS应用程序中运行良好的原因是应用程序启动默认的runloop,它根据UI更新通知等特定规则执行提交到主队列的任务。

参考如下:

swift-corelibs-libdispatch

Concurrency Programming Guide