gpt4 book ai didi

kotlin - 协程作用域被取消后,还可以再次使用吗?

转载 作者:行者123 更新时间:2023-12-03 16:31:57 72 4
gpt4 key购买 nike

当我们有了协程作用域,当它被取消后,还能再使用吗?
例如对于以下内容,当我有 scope.cancel 时, scope.launch不再工作

    @Test
fun testingLaunch() {
val scope = MainScope()
runBlocking {
scope.cancel()
scope.launch {
try {
println("Start Launch 2")
delay(200)
println("End Launch 2")
} catch (e: CancellationException) {
println("Cancellation Exception")
}
}.join()

println("Finished")
}
}
同样,当我们有 scope.cancel之前 await叫,
    @Test
fun testingAsync() {
val scope = MainScope()
runBlocking {
scope.cancel()
val defer = scope.async {
try {
println("Start Launch 2")
delay(200)
println("End Launch 2")
} catch (e: CancellationException) {
println("Cancellation Exception")
}
}
defer.await()
println("Finished")
}
}
它不会执行。相反,它会崩溃
kotlinx.coroutines.JobCancellationException: Job was cancelled
; job=SupervisorJobImpl{Cancelled}@39529185
at kotlinx.coroutines.JobSupport.cancel(JobSupport.kt:1579)
at kotlinx.coroutines.CoroutineScopeKt.cancel(CoroutineScope.kt:217)
at kotlinx.coroutines.CoroutineScopeKt.cancel$default(CoroutineScope.kt:215)
at com.example.coroutinerevise.CoroutineExperiment$testingAsync$1.invokeSuspend(CoroutineExperiment.kt:241)
at |b|b|b(Coroutine boundary.|b(|b)
at kotlinx.coroutines.DeferredCoroutine.await$suspendImpl(Builders.common.kt:101)
at com.example.coroutinerevise.CoroutineExperiment$testingAsync$1.invokeSuspend(CoroutineExperiment.kt:254)
Caused by: kotlinx.coroutines.JobCancellationException: Job was cancelled; job=SupervisorJobImpl{Cancelled}@39529185
at kotlinx.coroutines.JobSupport.cancel(JobSupport.kt:1579)
at kotlinx.coroutines.CoroutineScopeKt.cancel(CoroutineScope.kt:217)
at kotlinx.coroutines.CoroutineScopeKt.cancel$default(CoroutineScope.kt:215)
at com.example.coroutinerevise.CoroutineExperiment$testingAsync$1.invokeSuspend(CoroutineExperiment.kt:241)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
是否真的,取消的协程作用域不能用于 launchasync了?

最佳答案

而不是使用 CoroutineScope要取消其中的所有已启 Action 业,您可能需要使用基础 CoroutineContext与它的 cancelChildren()不影响Job的方法状态(对于普通的 cancel() 方法不是这样)并允许在调用后继续启动新的协程。

关于kotlin - 协程作用域被取消后,还可以再次使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65529095/

72 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com