不可取消的协程被取消

用户名

我正在尝试使用不可取消的协程,并编写了以下代码:

fun main(): Unit = runBlocking {
    // launch first coroutine
    coroutineScope {
        val job1 = launch {
            withContext(NonCancellable) {
                val delay = Random.nextLong(from = 500, until = 5000)
                println("Coroutine started. Waiting for ${delay}ms")
                delay(delay)
                println("Coroutine completed")
            }
        }

        delay(300) // let it print the first line
        println("Cancelling coroutine")
        job1.cancelAndJoin()
    }
}

输出:

Coroutine started. Waiting for 1313ms
Cancelling coroutine
Coroutine completed

到目前为止,一切都按预期进行。但是,如果我直接在函数中传递NonCancellable上下文(或更确切地说,Joblaunch,则行为会发生变化,协程将被取消:

fun main(): Unit = runBlocking {
    // launch first coroutine
    coroutineScope {
        val job1 = launch(context = NonCancellable) {
            val delay = Random.nextLong(from = 500, until = 5000)
            println("Coroutine started. Waiting for ${delay}ms")
            delay(delay)
            println("Coroutine completed")
        }

        delay(300) // let it print the first line
        println("Cancelling coroutine")
        job1.cancelAndJoin()
    }
}

输出:

Coroutine started. Waiting for 4996ms
Cancelling coroutine

为什么第二个片段产生不同的输出?

嘉宾21

您传递给launch方法的参数的工作不是启动的协程的工作,而是其父工作

在上面的第二个片段中,NonCancellable是的父作业job1由于job1只是正常工作,因此可以取消(但其父级则不能)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章