2

我想知道dispatch_async在以下表示为“A”和“B”的方法中使用之间有什么区别。

A

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    for (int i = 0; i < 10; i++)
    {
        // do something
    }
});

B

for (int i = 0; i < 10; i++)
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // do something

    });
}
4

2 回答 2

6

语句 A 产生一个新任务,该任务恰好包含一个循环。

语句 B 产生 10 个新任务,其中一些或全部可能要等到for循环完成之后才能完成。

于 2013-02-20T15:51:23.963 回答
0

Dispatch_async schedules whatever in the block between {} to run on the queue specified.

So in case A, the code is traversed without the for loop being executed. Instead, the forloop is moved to the block specified.

In case B, you are scheduling to run the code inside the block 10 times on a different thread. Frankly I have not seen this kind of combination.

If you are new to iOS, you will mainly use blocks in the context of doing some computing intensive work in a different queue than the main queue. This allows the UI to remain responsive (you can still scroll the table for example)... And then when you need to update the UI, you execute a block like the one above but calling the main queue to update your UI.

Hope this helps.

于 2013-02-20T15:52:22.990 回答