首页 > 解决方案 > 如何在 jvm kotlin 中使用 await 或 async?

问题描述

我正在尝试在 kotlin await/async 函数中编写一个示例,它应该与 ac# 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-等待

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
}

标签: asynchronouskotlinasync-awaitcoroutine

解决方案


async/await因为CreateMultipleTasksAsync并且startButton_Click是无用的。让它们suspend发挥作用。

并且 +1delay代替Thread.sleep


推荐阅读