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

标签 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
}

最佳答案

async/awaitCreateMultipleTasksAsyncstartButton_Click没用。
只需使它们成为suspend函数即可。

并为delay而不是Thread.sleep +1

关于asynchronous - 如何在JVM Kotlin中使用等待或异步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52677969/

相关文章:

Kotlin中数据类的继承

javascript - 如何在 JavaSCript 中将 JSON 数据存储在变量中?

asp.net - UpdatePanel 与 ASP.NET Repeater 和 Checkbox 同步回发问题

swift - 当我向下滚动并返回时,我的数据在 UITableViewCell 中发生变化

c# - 可以将委托(delegate)分配给匿名方法或 lambda,但不能分配给方法

c# - 放置异步/等待的最佳做法是什么?

android - 重新进入应用程序后如何在recyclerview中保存有关单击项位置的信息

android - horizo​​ntalArrangement 在 Jetpack Compose 中不起作用

c# - 任务处理的差异

javascript - async、await、promise 的响应未定义