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

当我们有了协程作用域,当它被取消后,还能再使用吗?

例如对于下面,当我有时scope.cancelscope.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用于取消其中的所有已启动作业,您可能希望将底层方法CoroutineContext与它的cancelChildren()方法一起使用,该方法不会影响Job状态(对于普通cancel()方法而言并非如此)并允许在调用后继续启动新的协程。


以上是协程作用域被取消后,还可以再次使用吗?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>