暂停功能块主线程
Suspend function blocks main thread
我很难理解协程。这是一个非常简单的设置。 longComputation
和 delay
都是挂起函数。第一个阻塞主线程,后者不会。为什么?
CoroutineScope(Dispatchers.Main).launch {
val result = longComputation() // Blocks
delay(10_000) // Doesn't block
}
这取决于。 longComputation
到底是做什么的?
当您将函数标记为 suspend
时,这并不意味着您不能在其中包含阻塞代码。例如,看看这个:
suspend fun blockingSuspendFunction(){
BigInteger(1500, Random()).nextProbablePrime()
}
suspend 函数中的代码显然是利用 CPU 并阻止调用者的代码。
按照惯例,不应这样做,因为如果您调用挂起函数,您期望它不是 阻塞线程:
Convention: suspending functions do not block the caller thread. (https://medium.com/@elizarov/blocking-threads-suspending-coroutines-d33e11bf4761)
要实现这样的功能 "behave as a suspending function",必须将阻塞分派到另一个工作线程,这(根据建议)应该发生在 withContext
:
suspend fun blockingSuspendFunction() = withContext(Dispatchers.Default) {
BigInteger.probablePrime(2048, Random())
}
我很难理解协程。这是一个非常简单的设置。 longComputation
和 delay
都是挂起函数。第一个阻塞主线程,后者不会。为什么?
CoroutineScope(Dispatchers.Main).launch {
val result = longComputation() // Blocks
delay(10_000) // Doesn't block
}
这取决于。 longComputation
到底是做什么的?
当您将函数标记为 suspend
时,这并不意味着您不能在其中包含阻塞代码。例如,看看这个:
suspend fun blockingSuspendFunction(){
BigInteger(1500, Random()).nextProbablePrime()
}
suspend 函数中的代码显然是利用 CPU 并阻止调用者的代码。 按照惯例,不应这样做,因为如果您调用挂起函数,您期望它不是 阻塞线程:
Convention: suspending functions do not block the caller thread. (https://medium.com/@elizarov/blocking-threads-suspending-coroutines-d33e11bf4761)
要实现这样的功能 "behave as a suspending function",必须将阻塞分派到另一个工作线程,这(根据建议)应该发生在 withContext
:
suspend fun blockingSuspendFunction() = withContext(Dispatchers.Default) {
BigInteger.probablePrime(2048, Random())
}