如何在JVM Kotlin中使用等待或异步?

时间:2018-10-06 10:12:25

标签: asynchronous kotlin async-await coroutine

我正在尝试在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
}

1 个答案:

答案 0 :(得分:1)

async/await对于CreateMultipleTasksAsyncstartButton_Click是没有用的。 只需使其具有suspend函数即可。

delay而不是Thread.sleep