我正在尝试在 Android 的后台运行任务,我想知道是否需要指定 GlobalScope.launch(Dispatchers.IO) { ... }
或者如果一个简单的 GlobalScope.launch { ... }
足够的。我担心的是第二种形式是否启动协程在主线程或后台/IO 线程中 ?
根据Android documentation ,
launch
doesn't take aDispatchers.IO
parameter. When you don't pass aDispatcher
to launch, any coroutines launched fromviewModelScope
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 asGlobalScope.launch { ... }
.
我知道协程直到最近还是实验性的,Android-Kotlin 与纯 Kotlin 开发是不同的,但这些陈述对我来说似乎是矛盾的。
最佳答案
GlobalScope有 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)
这样每次没有指定 dispatcher 的启动都会在 Main 中启动,类似于 viewModelScope
.
关于android - Kotlin 的启动是在主线程还是后台线程中启动协程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62574178/