Android 运行并行操作并获得结果-异步{…}是正确的方法吗?
安卓工作室3.6 我需要下一个:Android 运行并行操作并获得结果-异步{…}是正确的方法吗?,android,kotlin-coroutines,Android,Kotlin Coroutines,安卓工作室3.6 我需要下一个: 字符串列表(文件名) 每个方法doSomeLongOperation(fileName)都必须以并行执行和独立执行。例如,方法doSomeLongOperation(fileName1)不得等待方法doSomeLongOperation(fileName2)的响应 每个doSomeLongOperation(文件名)的结果都不同,必须添加到列表中 因此,假设doSomeLongOperation(fileName)的持续时间为5秒 所以如果我从12:00:00开
doSomeLongOperation(fileName)
都必须以并行执行和独立执行。例如,方法doSomeLongOperation(fileName1)
不得等待方法doSomeLongOperation(fileName2)
的响应doSomeLongOperation(文件名)
的结果都不同,必须添加到列表中doSomeLongOperation(fileName)
的持续时间为5秒
所以如果我从12:00:00开始,那么所有工作都必须在12:00:05完成
下面是一段:
suspend fun testParallel(filesList: List<String>) =
withContext(Dispatchers.IO) {
Debug.d(TAG, "testParallel: start, filesList = $filesList")
val resultList = mutableListOf<Deferred<Int>>()
filesList.forEach({
val result = async { doSomeLongOperation(it) }
resultList.add(result)
})
Debug.d(TAG, "testParallel: resultList = ${resultList.awaitAll()}")
}
suspend fun doSomeLongOperation(fileName: String): Int {
//val duration = 1000L * Random().nextInt(20)
val duration = 1000L * 5
Debug.d(TAG, "doSomeLongOperation: START, fileName = $fileName, duration = $duration")
delay(duration)
val random = Random().nextInt(100)
Debug.d(
TAG,
"doSomeLongOperation: FINISH, fileName = $fileName, duration = $duration, random = $random"
)
return random
}
如您所见,过程从01-28 17:57:19开始,所有方法在5秒后完成
01-28 17:57:24
每个dosomelong操作的结果
被添加到restulList
。
美好的很好。要做到这一切,我使用Kotlin的方法:async
问题是:
通过Kotlin的协同程序,这是一种正确的方法吗?是的:-)你在想什么呢?@Blundell我在Kotlin中找到了:GlobalScope.async{…}。与simple async{}有什么不同?simpleasync
用于运行挂起函数,GlobalScope.async{}
(如果我自己的理解正确的话)用于启动新的协同程序作用域(也就是启动线程)。请不要引用我的话:)但我不想不回答:Dasync
始终是async
,它是CoroutineScope
上的一个扩展函数,因此实际上您已经在某个范围上调用了它,这是隐式的this
,指的是与context
的范围。这是正确的,您无需等待即可启动所有异步,保留对延迟结果的引用,然后等待所有这些延迟结果以获得实际结果。(GlobalScope.async与myScope.async只是尝试将协同路由扩展到某个范围,因此您可以立即取消它们)
01-28 17:57:24