我正在尝试在kotlin await / async函数中编写一个示例,该示例应该与C#await示例相同。它可以正常工作,但没有错误,但是我不确定我是否正确理解它们,也许我创建了太多异步协程。有人可以给我一些建议吗?谢谢。
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/how-to-make-multiple-web-requests-in-parallel-by-using-async-and-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
函数即可。
并为delay
而不是Thread.sleep
+1
关于asynchronous - 如何在JVM Kotlin中使用等待或异步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52677969/