未解决的参考:GlobalScope.launch in vs code

unresolved reference: GlobalScope.launch in vs code

我在使用 Kotlin 中的协程时收到未解决的引用。我不知道如何在 vs code 上更新 build.gradle 文件。我是否必须导入一些扩展或路径?下面是代码

import kotlin.coroutines.*

fun main() {
    val states = arrayOf("Starting", "Doing Task 1", "Doing Task 2", "Ending")
    repeat(3) {
        GlobalScope.launch {
            println("${Thread.currentThread()} has started")
            for(i in states) {
                println("${Thread.currentThread()} - $i")
                delay(5000)
            }
        }
    }
}

输出给出了关于 GlobalScope.launch() 和 delay()

的未解决参考

GlobalScopelaunchdelay 不是 Kotlin 标准库的一部分,它们是 Kotlinx coroutines library.

的一部分

要使用它们,您需要将协同程序库添加到您的 build.gradle(.kts):

dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0")
}

然后导入这些声明:

import kotlinx.coroutines.*

附带说明一下,除非您知道自己在做什么,否则不应使用 GlobalScope,而且我猜您现在只是在学习协程,所以您可能希望避免使用它。通常,您应该使用与某个具有生命周期的组件相关联的协程作用域。

在这种情况下,您可能希望在 main 方法的主体周围使用 runBlocking { ... },这会在您等待协程时阻塞主线程。