13

我在玩协程,发现了一些非常奇怪的行为。我想在我的项目中使用suspendCoroutine(). 这是显示此问题的一段代码。

在第一种情况下,当在协程中调用挂起函数时runBlocking,来自延续的异常进入 catch 块,然后runBlocking成功完成。但是在第二种情况下,当创建新的async协程时,异常会通过 catch 块并导致整个程序崩溃。

package com.example.lib

import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

object Test {
    fun runSuccessfulCoroutine() {
        runBlocking {
            try {
                Repository.fail()
            } catch (ex: Throwable) {
                println("Catching ex in runSuccessfulCoroutine(): $ex")
            }
        }
    }

    fun runFailingCoroutine() {
        runBlocking {
            try {
                async { Repository.fail() }.await()
            } catch (ex: Throwable) {
                println("Catching ex in runFailingCoroutine(): $ex")
            }
        }
    }
}

object Repository {
    suspend fun fail(): Int = suspendCoroutine { cont ->
        cont.resumeWithException(RuntimeException("Exception at ${Thread.currentThread().name}"))
    }
}


fun main() {
    Test.runSuccessfulCoroutine()
    println()

    Test.runFailingCoroutine()

    println("We will never get here")
}

这就是控制台上打印的内容:

Catching ex in runSuccessfulCoroutine(): java.lang.RuntimeException: Exception at main

Catching ex in runFailingCoroutine(): java.lang.RuntimeException: Exception at main
Exception in thread "main" java.lang.RuntimeException: Exception at main
    at com.example.lib.Repository.fail(MyClass.kt:32)
    at com.example.lib.Test$runFailingCoroutine$1$1.invokeSuspend(MyClass.kt:22)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:32)
    at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:236)
    at kotlinx.coroutines.EventLoopBase.processNextEvent(EventLoop.kt:123)
    at kotlinx.coroutines.BlockingCoroutine.joinBlocking(Builders.kt:69)
    at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking(Builders.kt:45)
    at kotlinx.coroutines.BuildersKt.runBlocking(Unknown Source)
    at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking$default(Builders.kt:35)
    at kotlinx.coroutines.BuildersKt.runBlocking$default(Unknown Source)
    at com.example.lib.Test.runFailingCoroutine(MyClass.kt:20)
    at com.example.lib.MyClassKt.main(MyClass.kt:41)
    at com.example.lib.MyClassKt.main(MyClass.kt)

Process finished with exit code 1

任何想法为什么会发生这种情况 - 它是一个错误,还是我以错误的方式使用协程?

更新:

使用coroutineScope { ... }将缓解问题runFailingCoroutine()

fun runFailingCoroutine() = runBlocking {
    try {
        coroutineScope { async { fail() }.await()  }
    } catch (ex: Throwable) {
        println("Catching ex in runFailingCoroutine(): $ex")
    }
}
4

2 回答 2

8

您的第二个示例的行为是正确的,这是结构化并发的工作。因为内部async块抛出了异常,所以这个协程被取消了。由于结构化并发,父作业也被取消。

看这个小例子:

val result = coroutineScope {
    async {
        throw IllegalStateException()
    }
    10
}

这个块永远不会返回一个值,即使我们从不请求async结果。内部协程被取消,外部范围也被取消。

如果你不喜欢这种行为,你可以使用supervisorScope. 在这种情况下,内部协程可能会失败,而外部协程不会失败。

val result = supervisorScope {
    async {
        throw IllegalStateException()
    }
    10
}

在您的第一个示例中,您在协程块内捕获异常,因此,协程正常退出。

有关此主题的讨论,请参阅:

于 2018-11-10T16:14:43.067 回答
6

就在昨天,我对这种行为感到震惊,这是我的分析

简而言之,这种行为是需要的,因为async它与其他语言的目的不同。在 Kotlin 中,您应该谨慎使用它,仅当您必须将一个任务分解为多个并行运行的子任务时。

每当你只想写

val result = async { work() }.await()

你应该改写

val result = withContext(Default) { work() }

这将表现出预期的方式。此外,只要有机会,您应该将withContext调用移到work()函数中并将其设为suspend fun.

于 2018-11-10T16:31:12.583 回答