挂起功能块主线程

问题描述 投票:1回答:1

我很难理解协同程序。这是一个非常简单的设置。 longComputationdelay都是暂停功能。第一个阻塞主线程,后者不阻塞。为什么?

CoroutineScope(Dispatchers.Main).launch {
    val result = longComputation() // Blocks
    delay(10_000) // Doesn't block
}
kotlin kotlin-android-extensions kotlin-coroutines
1个回答
3
投票

那要看。 longComputation到底做了什么?将函数标记为suspend时,这并不意味着您不能在其中包含阻塞代码。例如,看看这个:

suspend fun blockingSuspendFunction(){
    BigInteger(1500, Random()).nextProbablePrime()
}

暂停函数内的代码显然是利用CPU并阻止调用者的东西。按照惯例,这不应该这样做,因为如果你调用一个挂起函数,你希望它不会阻塞线程:

约定:挂起函数不会阻止调用者线程。 (https://medium.com/@elizarov/blocking-threads-suspending-coroutines-d33e11bf4761

要使这样的函数“充当挂起函数”,必须将阻塞分派到另一个工作线程上,(通过建议)应该使用withContext

suspend fun blockingSuspendFunction() = withContext(Dispatchers.Default) {
    BigInteger.probablePrime(2048, Random())
}
© www.soinside.com 2019 - 2024. All rights reserved.