Kotlin 的启动是在主线程还是后台线程中启动协程?

Does Kotlin's launch start a coroutine in the main or a background thread?

我正在尝试 运行 Android 的后台任务,我想知道我是否需要指定 GlobalScope.launch(Dispatchers.IO) { ... } 或者是否需要一个简单的 GlobalScope.launch { ... }足够。我担心的是第二种形式是启动协程 in main 还是 background/IO thread?


根据Android documentation,

launch doesn't take a Dispatchers.IO parameter. When you don't pass a Dispatcher to launch, any coroutines launched from viewModelScope run in the main thread.

根据Kotlin documentation,

The default dispatcher that is used when coroutines are launched in GlobalScope is represented by Dispatchers.Default and uses a shared background pool of threads, so launch(Dispatchers.Default) { ... } uses the same dispatcher as GlobalScope.launch { ... }.

我知道协程直到最近都是实验性的,Android-Kotlin 与纯 Kotlin 开发是不同的,但这些说法对我来说似乎是矛盾的。

GlobalScope has EmptyCoroutineContext 这意味着 Dispatchers.Default 将在其中直接启动时使用。

行为示例:https://pl.kotl.in/cLy3UfuZO

My worry is whether the second form launches the coroutine in the main or a background/IO thread?

它将在 Dispatchers.Default 下将其启动到 CommonPool 中,共享最大线程与 CPU 中的内核数相同,例如,如果您的 CPU 有 6 个内核,那么会有最大限制为 6 个线程。 Dispatchers.IO 但是最多允许从 CommonPool 借用 64 个线程。 Dispatchers.Main 是单线程的。


viewModelScope 的故事不同,该范围包含 Dispatchers.Main 作为其启动的默认调度程序。您可以创建这样的范围 CoroutineScope(Dispatchers.Main),以便每次启动时无需指定调度程序将在 Main 中启动,类似于 viewModelScope.