且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

dispatch_async(dispatch_get_main_queue(),^ {...});等到完成?

更新时间:2023-10-06 12:54:10

不,它没有等待,你在这个样本中做的方式不是好习惯。

No it doesn't wait and the way you are doing it in that sample is not good practice.

dispatch_async 始终是异步。只是您将所有UI块排入同一队列,因此不同的块将按顺序运行,但与您的数据处理代码并行。

dispatch_async is always asynchronous. It's just that you are enqueueing all the UI blocks to the same queue so the different blocks will run in sequence but parallel with your data processing code.

如果您希望更新等待,可以改用 dispatch_sync

If you want the update to wait you can use dispatch_sync instead.

// This will wait to finish
dispatch_sync(dispatch_get_main_queue(), ^{
    // Update the UI on the main thread.
});

另一种方法是嵌套排队。我不会推荐它用于多个级别。

Another approach would be to nest enqueueing the block. I wouldn't recommend it for multiple levels though.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Background work

    dispatch_async(dispatch_get_main_queue(), ^{
        // Update UI

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // Background work

            dispatch_async(dispatch_get_main_queue(), ^{
                // Update UI
            });
        });
    });
});

如果您需要更新UI以等待,那么您应该使用同步版本。有一个后台线程等待主线程是完全可以的。 UI更新应该非常快。

If you need the UI updated to wait then you should use the synchronous versions. It's quite okay to have a background thread wait for the main thread. UI updates should be very quick.