Kotlin协程:等待多个线程完成 [英] Kotlin Coroutines : Waiting for multiple threads to finish

查看:1077
本文介绍了Kotlin协程:等待多个线程完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,第一次查看协程,我想并行处理数据加载并等待其完成.我环顾四周,看到RunBlocking和Await等,但不确定如何使用它.

So looking at Coroutines for the first time, I want to process a load of data in parallel and wait for it to finish. I been looking around and seen RunBlocking and Await etc but not sure how to use it.

我到目前为止有

val jobs = mutableListOf<Job>()
jobs += GlobalScope.launch { processPages(urls, collection) }
jobs += GlobalScope.launch { processPages(urls, collection2) }
jobs += GlobalScope.launch { processPages(urls, collection3) }

然后我想知道/等待这些完成

I then want to know/wait for these to finish

推荐答案

如果您使用结构化并发概念,则无需手动跟踪当前的工作.假设您的processPages函数执行某种阻塞的IO,则可以将代码封装到以下挂起函数中,该函数在为此工作而设计的IO调度程序中执行代码:

You don't need to manually keep track of your cuncurrent jobs if you use the concept of structured concurrency. Assuming that your processPages function performs some kind of blocking IO, you can encapsulate your code into the following suspending function, which executes your code in an IO dispatcher designed for this kind of work:

suspend fun processAllPages() = withContext(Dispatchers.IO) { 
    // withContext waits for all children coroutines 
    launch { processPages(urls, collection) }
    launch { processPages(urls, collection2) }
    launch { processPages(urls, collection3) }
}

现在,如果应用程序的最高功能还不是挂起功能,则可以使用runBlocking调用processAllPages:

Now, from if a topmost function of your application is not already a suspending function, then you can use runBlocking to call processAllPages:

runBlocking {
    processAllPages()
}

这篇关于Kotlin协程:等待多个线程完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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