首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >withContext与suspendCancellableCoroutine的区别

withContext与suspendCancellableCoroutine的区别
EN

Stack Overflow用户
提问于 2020-05-13 13:09:18
回答 2查看 1.1K关注 0票数 2

我是新来的

这是一个很流行的例子:

代码语言:javascript
复制
suspend fun findBigPrime(): BigInteger =
    withContext(Dispatchers.IO) {
        BigInteger.probablePrime(4096, Random()))
    }

但是,可以编写它,也可以:

代码语言:javascript
复制
suspend fun findBigPrime(): BigInteger =
    suspendCancellableCoroutine {
        it.resume(BigInteger.probablePrime(4096, Random()))
    }

真正的区别是什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-05-13 14:15:23

,真正的区别是什么?

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

代码语言:javascript
复制
suspendCancellableCoroutine {
    it.resume(BigInteger.probablePrime(4096, Random()))
}

这只会在简单的直接呼叫之上增加无用的开销。

代码语言:javascript
复制
BigInteger.probablePrime(4096, Random())

如果继续在suspendCancellableCoroutine块中继续,协同线根本不会挂起。

代码语言:javascript
复制
withContext(Dispatchers.IO) {
    BigInteger.probablePrime(4096, Random()))
}

这将暂停协同线,并在另一个线程上启动内部协同线。当内部协同线完成后,它将恢复当前的协同,并得到结果。

票数 3
EN

Stack Overflow用户

发布于 2020-05-13 13:22:42

在这里使用suspendCancellableCoroutine是“大不”。

withContext更改块( coroutine )将在其上运行的上下文,在这里,向指定线程分派协同线的调度程序将被重写。虽然suspendCoroutine/suspendCancellableCoroutine用于包装异步回调,但它不会阻塞线程,而是在自己的线程上运行。

通常,suspendCoroutine/suspendCancellableCoroutine上的工作是非阻塞的,并且完成得很快,并且在工作以非阻塞的方式完成之后,可能在其他线程中继续工作。

如果将阻塞代码放入其中-- coroutine的概念丢失了,那么它就会阻塞正在运行的线程。

suspendCoroutine**/**suspendCancellableCoroutine**:**的使用

代码语言:javascript
复制
// 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)
        }
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61775505

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档