1

我对异步加载和主线程的概念有点困惑。当某些东西异步加载时,是否意味着它不在主线程上运行?据我所知,这是两个不同的概念,可以在主线程上异步运行,也可以在后台/辅助线程上异步运行。如果我错了,请纠正我。

4

3 回答 3

6

Not quite. Running asynchronously means that it doesn't stop execution from continuing on the current thread. This is an important difference because it's totally possible to do something asynchronously such that it ends up on the main thread (for example: dispatch_async(dispatch_get_main_queue(), ^{ some block });), which would mean that it's not stopping some other thread from continuing, but is blocking the main thread.

Because the main thread is so important to applications, the most common use of asynchronous code is to avoid blocking it, but it's not the only use.

(edited to add)

It's more useful, perhaps, to think of it in terms of "async with respect to x". If you do this, for example:

dispatch_async(aSerialQueue, ^{
    work();
    work();
});

Then the two invocations of work are synchronous with respect to each other, and synchronous with respect to all other work on aSerialQueue, but asynchronous with respect to everything else.

于 2013-02-07T23:41:56.773 回答
2

异步运行只是意味着调用可能会在任务完成之前返回。这可能是因为它在后台线程上运行。可能是因为它稍后会在当前线程上发生。

同步运行并不意味着它会发生在主线程上;这意味着在任务完成之前调用不会返回。那可能是因为它发生在同一个线程上。可能是因为它发生在另一个线程上,但您希望当前线程等待另一个线程完成。

此外,请注意主线程和当前线程之间存在差异。在后台线程上调用的同步任务将阻止该后台线程继续运行,直到任务完成,但根本不会阻塞主线程。

当然,在 iOS 中大部分时间,您的代码将在主线程上运行。但是您可以将工作推送到后台线程(例如使用dispatchAPI),因此区别很重要。

于 2013-02-07T23:45:52.490 回答
0

主线程是执行大部分代码的地方,包括所有 UI。还有其他线程,例如网络线程和网络线程,您可以创建自己的线程。

同步与异步是您的代码何时执行的问题。您可以在主线程或任何其他线程上执行同步或异步代码块。如果它是同步的,它将阻塞线程的其余部分,直到它完成。如果它是异步的,它将在线程从当前正在执行的任何事情中释放出来时运行。

于 2013-02-07T23:45:30.177 回答