如何加入Kotlin主管职位 [英] How to join a Kotlin SupervisorJob

查看:78
本文介绍了如何加入Kotlin主管职位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试处理数据对象树.假定每个树叶都应使用协程通过一个函数进行处理.整个过程应使用固定大小的线程池完成.

I am trying to process a tree of data objects. Each tree leaf is supposed to be processed through a function using a coroutine. The whole process should be done using a fixed size threadpool.

所以我想到了这个:

val node = an instance of WorkspaceEntry (tree structure)
val localDispatcher = newFixedThreadPoolContext(16)

fun main() {
    val job = SupervisorJob()
    val scope = CoroutineScope(localDispatcher + job)
    handleEntry(node, scope)

    runBlocking {
        job.join()
    }
}

handleEntry方法为每个叶子递归在主管中启动一个子作业.

The handleEntry method recursively launches a child job in the supervisor for each tree leaf.

主管的子作业全部成功完成,但联接永不返回.我是否理解错了?

The child jobs of the supervisor all complete successfully, but the join never returns. Am I understanding this wrong?

HandleEntry函数

HandleEntry function

private fun handleEntry(workspaceEntry: WorkspaceEntry, scope: CoroutineScope) {
    if (workspaceEntry is FileEntry) {
        scope.launch {
            FileTypeRegistry.processFile(workspaceEntry.fileBlob)
        }
    } else {
        workspaceEntry.children.forEach { child -> handleEntry(child, scope) }
    }
}

推荐答案

似乎用于创建CoroutineContextJob(在您的情况下为SupervisorJob)并不是要等待子协程完成的,所以您不能使用job.join().我想Job的主要目的是取消子协程.将runBlocking块更改为以下内容将起作用:

It seems the Job that is used to create CoroutineContext (in your case SupervisorJob) is not intended for waiting child coroutines to finish, so you can't use job.join(). I guess the main intent of that Job is to cancel child coroutines. Changing runBlocking block to the following will work:

runBlocking {
    job.children.forEach {
        it.join()
    }
}

这篇关于如何加入Kotlin主管职位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆