我是新来的
这是一个很流行的例子:
suspend fun findBigPrime(): BigInteger =
withContext(Dispatchers.IO) {
BigInteger.probablePrime(4096, Random()))
}但是,可以编写它,也可以:
suspend fun findBigPrime(): BigInteger =
suspendCancellableCoroutine {
it.resume(BigInteger.probablePrime(4096, Random()))
}真正的区别是什么?
发布于 2020-05-13 14:15:23
,真正的区别是什么?
事实上,几乎没有任何关系。
suspendCancellableCoroutine {
it.resume(BigInteger.probablePrime(4096, Random()))
}这只会在简单的直接呼叫之上增加无用的开销。
BigInteger.probablePrime(4096, Random())如果继续在suspendCancellableCoroutine块中继续,协同线根本不会挂起。
withContext(Dispatchers.IO) {
BigInteger.probablePrime(4096, Random()))
}这将暂停协同线,并在另一个线程上启动内部协同线。当内部协同线完成后,它将恢复当前的协同,并得到结果。
发布于 2020-05-13 13:22:42
在这里使用suspendCancellableCoroutine是“大不”。
withContext更改块( coroutine )将在其上运行的上下文,在这里,向指定线程分派协同线的调度程序将被重写。虽然suspendCoroutine/suspendCancellableCoroutine用于包装异步回调,但它不会阻塞线程,而是在自己的线程上运行。
通常,suspendCoroutine/suspendCancellableCoroutine上的工作是非阻塞的,并且完成得很快,并且在工作以非阻塞的方式完成之后,可能在其他线程中继续工作。
如果将阻塞代码放入其中-- coroutine的概念丢失了,那么它就会阻塞正在运行的线程。
suspendCoroutine**/**suspendCancellableCoroutine**:**的使用
// This function immediately creates and starts thread and returns
fun findBigPrimeInNewThread(after: (BigInteger) -> Unit) {
Thread {
BigInteger.probablePrime(4096, Random()).also(after)
}
}
// This just wraps the async function so that when the result is ready resume the coroutine
suspend fun findBigPrime(): BigInteger =
suspendCancellableCoroutine { cont ->
findBigPrimeInNewThread {
cont.resume(it)
}
}https://stackoverflow.com/questions/61775505
复制相似问题