作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在协程中,当我想保护一段代码不被取消时,我应该将 NonCancellable 添加到上下文中:
@Test
fun coroutineCancellation_NonCancellable() {
runBlocking {
val scopeJob = Job()
val scope = CoroutineScope(scopeJob + Dispatchers.Default + CoroutineName("outer scope"))
val launchJob = scope.launch(CoroutineName("cancelled coroutine")) {
launch (CoroutineName("nested coroutine")) {
withContext(NonCancellable) {
delay(1000)
}
}
}
scope.launch {
delay(100)
launchJob.cancel()
}
launchJob.join()
}
}
上面的单元测试将需要大约 1.1 秒的时间来执行,即使长时间运行的协程在 100 毫秒后被取消。这就是 NonCancellable 的效果,我理解这一点。
@Test
fun coroutineCancellation_newJobInsteadOfNonCancellable() {
runBlocking {
val scopeJob = Job()
val scope = CoroutineScope(scopeJob + Dispatchers.Default + CoroutineName("outer scope"))
val launchJob = scope.launch(CoroutineName("cancelled coroutine")) {
launch (CoroutineName("nested coroutine")) {
withContext(Job()) {
delay(1000)
}
}
}
scope.launch {
delay(100)
launchJob.cancel()
}
launchJob.join()
}
}
我试图在取消、错误处理和一般功能方面找到这两种方法之间的任何功能差异,但到目前为止我没有发现。目前,看起来 NonCancellable 在框架中只是为了便于阅读。
@Test
fun coroutineCancellation_jobInsteadOfNonCancellableInCleanup() {
runBlocking {
val scope = CoroutineScope(Job() + Dispatchers.Default + CoroutineName("outer scope"))
val launchJob = scope.launch(CoroutineName("test coroutine")) {
try {
delay(100)
throw java.lang.RuntimeException()
} catch (e: Exception) {
withContext(Job()) {
cleanup()
}
}
}
scope.launch {
delay(200)
launchJob.cancel()
}
launchJob.join()
}
}
private suspend fun cleanup() {
delay(1000)
}
最佳答案
NonCancellable
不响应取消,而 Job()
做。NonCancellable
实现 Job
以自定义方式,它与 Job()
的行为不同那是使用可取消的实现。cancel()
在 NonCancellable
是无操作的,不像 Job()
它将取消任何子协程,并且子协程中的任何崩溃都会传播到该父协程 Job
.
关于Kotlin 协程 : what's the diffrence between using NonCancellable and a standalone new Job,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64389648/
在协程中,当我想保护一段代码不被取消时,我应该将 NonCancellable 添加到上下文中: @Test fun coroutineCancellation_NonCancellable() {
我是一名优秀的程序员,十分优秀!