【发布时间】:2018-10-06 10:12:25
【问题描述】:
我正在尝试在 kotlin await/async 函数中编写一个示例,它应该与 c# await 示例一样工作。它可以正常工作,但我不确定我是否正确理解它们,也许我创建了太多异步协程。任何人都可以给我一些建议吗?谢谢。
package diki.test
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.runBlocking
import org.apache.commons.lang3.RandomUtils
fun main(args: Array<String>) = runBlocking {
val start = System.currentTimeMillis()
startButton_Click().await();
println("time=" + (System.currentTimeMillis() - start))
}
fun startButton_Click() = async {
CreateMultipleTasksAsync().await()
}
fun CreateMultipleTasksAsync() = async {
val d1 = ProcessURLAsync("http://a")
val d2 = ProcessURLAsync("http://a1")
val d3 = ProcessURLAsync("http://a111")
val d1r = d1.await()
val d2r = d2.await()
val d3r = d3.await()
}
fun ProcessURLAsync(url: String) = async {
Thread.sleep(RandomUtils.nextLong(500, 1000))//mock network job
url.length
}
【问题讨论】:
-
使用
delay协程代替Thread.sleep()。也看看awaitAll()
标签: asynchronous kotlin async-await coroutine