gpt4 book ai didi

Kotlin 协程 GlobalScope.launch 与 runBlocking

转载 作者:行者123 更新时间:2023-12-04 16:12:19 27 4
gpt4 key购买 nike

这两种方法有什么区别吗?

runBlocking {
launch(coroutineDispatcher) {
// job
}
}
GlobalScope.launch(coroutineDispatcher) {
// job
}

最佳答案

runBlocking runs new coroutine and blocks current thread interruptibly until its completion. This function should not be used from coroutine. It is designed to bridge regular blocking code to libraries that are written in suspending style, to be used in main functions and in tests.


// line 1
runBlocking {
// line 2
launch(coroutineDispatcher) {
// line 3
}
// line 4
}
// line 5
someFunction()

如果使用 runBlocking代码行将按以下顺序执行:
line 1
line 2
line 4
line 3
line 5 // this line will be executed after coroutine is finished

Global scope is used to launch top-level coroutines which are operating on the whole application lifetime and are not cancelled prematurely. Another use of the global scope is operators running in Dispatchers.Unconfined, which don't have any job associated with them. Application code usually should use application-defined CoroutineScope, using async or launch on the instance of GlobalScope is highly discouraged.


// line 1
GlobalScope.launch(coroutineDispatcher) {
// line 2
}
// line 3
someFunction()

如果使用 GlobalScope.launch代码行将按以下顺序执行:
line 1
line 3
line 2

因此 runBlocking阻塞当前线程直到它完成, GlobalScope.launch没有。

关于Kotlin 协程 GlobalScope.launch 与 runBlocking,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54842169/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com