asynchronous - 如何在 jvm kotlin 中使用 await 或 async?
问题描述
我正在尝试在 kotlin await/async 函数中编写一个示例,它应该与 ac# 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
}
解决方案
async/await
因为CreateMultipleTasksAsync
并且startButton_Click
是无用的。让它们suspend
发挥作用。
并且 +1delay
代替Thread.sleep
推荐阅读
- java - 从类中调用活动函数
- angular - Bootstrap 4:col-md-6 div右侧的大边距
- mysql - 在 MySQL 中使用 GROUP BY 时间范围时如何显示范围边界
- sql - 这可能与 SQL Server
- python - 编译的 Python 脚本不起作用
- c - 使用 C 获取文本文件中两个特定点之间的特定信息
- php - 我如何在另一个区域内使用带有变量名的 php 变量,就好像我自己键入变量名一样?
- python - “从 xy 导入 z”和“将 xyz 导入为 z”之间的区别
- angular - 如何让 Angular 5 在构造依赖项或 ngOnInit 之前等待 Injectable 构造函数中使用的 Promise 解析?
- c - 将两个字符连接成每个索引中的字符数组