首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么CoroutineExceptionHandler只能在coroutineContext是MainScope()时执行启动?

为什么CoroutineExceptionHandler只能在coroutineContext是MainScope()时执行启动?
EN

Stack Overflow用户
提问于 2021-01-02 05:45:07
回答 1查看 413关注 0票数 0

我有下面的代码,并故意触发一个要被errorHandler捕获的异常

代码语言:javascript
运行
复制
    private var coroutineScope: CoroutineScope? = null
    private val mainThreadSurrogate = newSingleThreadContext("Test Main")

    @Before
    fun setUp() {
        Dispatchers.setMain(mainThreadSurrogate)
    }

    @After
    fun tearDown() {
        // reset main dispatcher to the original Main dispatcher       
        Dispatchers.resetMain()
        mainThreadSurrogate.close()
    }

    private val errorHandler = CoroutineExceptionHandler { context, error ->
        println("Launch Exception ${Thread.currentThread()}")
        coroutineScope?.launch(Dispatchers.Main) {
            println("Launch Exception Result ${Thread.currentThread()}")
        }
    }

    @Test
    fun testData() {
        runBlocking {
            coroutineScope = MainScope()
            coroutineScope?.launch(errorHandler) {
                println("Launch Fetch Started ${Thread.currentThread()}")
                throw IllegalStateException("error")
            }?.join()
        }
    }

这将导致

代码语言:javascript
运行
复制
Launch Fetch Started Thread[Test Main @coroutine#2,5,main]
Launch Exception Thread[Test Main @coroutine#2,5,main]
Launch Exception Result Thread[Test Main @coroutine#3,5,main]

如果我将coroutineScope = MainScope()改为

  • coroutineScope = CoroutineScope(Dispatchers.Main)
  • coroutineScope = CoroutineScope(Dispatchers.IO)

coroutineScope?.launch(Dispatchers.Main) {...}不会运行,也就是说,Launch Exception Result ...不会被打印。

为什么会这样呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-02 07:22:58

显然,我们需要使用SupervisorJob()创建一个作用域,以便父作业不受子作业崩溃的影响。

代码语言:javascript
运行
复制
coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)

注意,MainScope()CoroutineScope(SupervisorJob() + Dispatchers.Main)

正如SupervisorJob中提到的

子任务的失败或取消不会导致主管作业失败,也不会影响其其他子任务,因此主管可以实施自定义策略来处理其子任务的

故障。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65536366

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档