【问题标题】:how to use await or async in jvm kotlin?如何在 jvm kotlin 中使用 await 或 async?
【发布时间】:2018-10-06 10:12:25
【问题描述】:

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

【问题讨论】:

标签: asynchronous kotlin async-await coroutine


【解决方案1】:

async/await 对于CreateMultipleTasksAsyncstartButton_Click 是没用的。 只需将它们设为suspend 函数即可。

delay +1 而不是Thread.sleep

【讨论】:

    猜你喜欢
    • 2012-03-02
    • 1970-01-01
    • 2019-07-20
    • 2021-10-10
    • 2019-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    相关资源
    最近更新 更多