Kotlin withContext和SuspendCancelableCorroutine之间的差异

Kotlin withContext和SuspendCancelableCorroutine之间的差异,kotlin,kotlin-coroutines,Kotlin,Kotlin Coroutines,我是新来的同事 这是一个流行的例子: suspend fun findBigPrime(): BigInteger = withContext(Dispatchers.IO) { BigInteger.probablePrime(4096, Random())) } 但是,它也可以写成: suspend fun findBigPrime(): BigInteger = suspendCancellableCoroutine { it.re

我是新来的同事

这是一个流行的例子:

suspend fun findBigPrime(): BigInteger =
    withContext(Dispatchers.IO) {
        BigInteger.probablePrime(4096, Random()))
    }
但是,它也可以写成:

suspend fun findBigPrime(): BigInteger =
    suspendCancellableCoroutine {
        it.resume(BigInteger.probablePrime(4096, Random()))
    }
真正的区别是什么

这里使用SuspendCancelableCorroutine是一个很大的禁忌

withContext更改块协同路由将在其上运行的上下文,这里将覆盖将协同路由分派到指定线程的调度程序。虽然suspendCoroutine/SuspendCancelableCoroutine用于包装异步回调,但异步回调不会阻塞线程,而是在自己的线程上运行

通常,在SuspendCorroutine/SuspendCancelableCorroutine上的工作是非阻塞的,并且可以很快完成,并且在工作以非阻塞的方式完成后,可以在其他线程中继续进行

如果你把阻塞代码放在那里,协同程序的概念就丢失了,它只会阻塞它正在运行的线程

SuspendCorroutine/SuspendCancelableCorroutine的使用:

//此函数立即创建和启动线程并返回 fun findBigPrimeInNewThreadafter:BigInteger->Unit{ 线{ BigInteger.probablePrime4096,Random.alsoafter } } //这只是包装了async函数,以便在结果就绪时恢复协同路由 suspend fun findBigPrime:BigInteger= SuspendCancelableCoroutine{cont-> findBigPrimeInNewThread{ 续 } } 在这里使用SuspendCancelableCoroutine是一个很大的禁忌

withContext更改块协同路由将在其上运行的上下文,这里将覆盖将协同路由分派到指定线程的调度程序。虽然suspendCoroutine/SuspendCancelableCoroutine用于包装异步回调,但异步回调不会阻塞线程,而是在自己的线程上运行

通常,在SuspendCorroutine/SuspendCancelableCorroutine上的工作是非阻塞的,并且可以很快完成,并且在工作以非阻塞的方式完成后,可以在其他线程中继续进行

如果你把阻塞代码放在那里,协同程序的概念就丢失了,它只会阻塞它正在运行的线程

SuspendCorroutine/SuspendCancelableCorroutine的使用:

//此函数立即创建和启动线程并返回 fun findBigPrimeInNewThreadafter:BigInteger->Unit{ 线{ BigInteger.probablePrime4096,Random.alsoafter } } //这只是包装了async函数,以便在结果就绪时恢复协同路由 suspend fun findBigPrime:BigInteger= SuspendCancelableCoroutine{cont-> findBigPrimeInNewThread{ 续 } } 真正的区别是什么

事实上,几乎没有任何关系

suspendCancellableCoroutine {
    it.resume(BigInteger.probablePrime(4096, Random()))
}
这只会在简单的直接调用之上增加无用的开销

BigInteger.probablePrime(4096, Random())
如果仍然在SuspendCancelableCoroutine块内继续,则coroutine根本不会挂起

withContext(Dispatchers.IO) {
    BigInteger.probablePrime(4096, Random()))
}
这将挂起协同路由并在另一个线程上启动内部协同路由。当内部协同程序完成时,它将恢复当前协同程序,并返回结果

真正的区别是什么

事实上,几乎没有任何关系

suspendCancellableCoroutine {
    it.resume(BigInteger.probablePrime(4096, Random()))
}
这只会在简单的直接调用之上增加无用的开销

BigInteger.probablePrime(4096, Random())
如果仍然在SuspendCancelableCoroutine块内继续,则coroutine根本不会挂起

withContext(Dispatchers.IO) {
    BigInteger.probablePrime(4096, Random()))
}
这将挂起协同路由并在另一个线程上启动内部协同路由。当内部协同程序完成时,它将恢复当前协同程序,并返回结果