ios - 了解并发 GCD

标签 ios multithreading asynchronous gcdasyncsocket

问题很简单,但我没能找到合理的答案。 在这样的代码中

dispatch_queue_t background_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, NULL);

dispatch_async(background_queue, ^{
// do some stuff that takes a long time here...

    // follow up with some stuff on the main queue
    dispatch_async(dispatch_get_main_queue(), ^{
        // Typically updating the UI on the main thread.
    });

});

“background_queue”是一个并发队列,因此其中的任务将按顺序开始,但可能不会按相同的顺序完成。所以我们可以在下载图像之前调用更新 UI 的 block 。 更多的说明会有所帮助,谢谢。

最佳答案

在这个例子中,两个GCD block 将按顺序完成,因为外部 block 只会在长进程完成后调用内部 block (更正确地说,它可能应该是一个dispatch_sync 在内 block 上)

这将保证顺序,因为后台线程将在主线程即将完成之前以及长任务完成之后调用 gcd block

dispatch_async(background_queue, ^{
// do some stuff that takes a long time here...

    // follow up with some stuff on the main queue
    dispatch_sync(dispatch_get_main_queue(), ^{ //should be sync not async, but in practice should have little impact if nothing happens after this block
        // Typically updating the UI on the main thread.
    });
});

这不会,因为两个 gcd block 将同时执行并且不会等待对方完成

dispatch_async(background_queue, ^{
// do some stuff that takes a long time here...
});
// follow up with some stuff on the main queue
dispatch_async(dispatch_get_main_queue(), ^{
   // Typically updating the UI on the main thread.
});

关于ios - 了解并发 GCD,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42063569/

相关文章:

ios - 在一个 .m 文件中无法识别 Google Analytics

ios - 在设备关闭时处理应用程序

iphone - UIButton 的双边框

Spring 未将 bean 注入(inject)线程

java - Netty 因多个客户端连接而卡住

javascript - Async-await 'Promise {<pending>} with Array.prototype.map

ios - 使用 object_setIvar 时的 EXC_BAD_ACCESS

java - ReentrantReadWriteLock - 一次有很多读者,一次有一个作者?

java - 如何使用多线程聚合两个 Web 服务?

javascript - 在命令运行时在 Grunt 中显示输出?