gpt4 book ai didi

android - 协程没有并行运行

转载 作者:行者123 更新时间:2023-12-02 12:44:14 24 4
gpt4 key购买 nike

我的 WorkManager 中有一些挂起函数可以进行网络调用我试图使用协程并行运行所以我试图使用 async在它们中,但它们似乎仍然是按顺序执行的。
例子:

suspend fun call1() = withContext(Dispatchers.IO){
async{
Log.d(TAG,"Call 1 started")
delay(2000)
Log.d(TAG,"Call 1 fiished")
}
}

suspend fun call2() = withContext(Dispatchers.IO){
async{
Log.d(TAG,"Call 2 started")
delay(5000)
Log.d(TAG,"Call 2 finished")
}
}

suspend fun call3() = withContext(Dispatchers.IO){
async{
Log.d(TAG,"Call 3 started")
delay(1000)
Log.d(TAG,"Call 3 finished")
}
}
我这样称呼他们
override suspend fun doWork(): Result{
setForeground(createForegroundInfo())
call1()
call2()
call3()
return Result.success()
}
当我运行它时,我看到日志消息按顺序显示,就像它们被调用一样,下一个调用直到前一个调用完成才会开始。我期待的是 call3先完成然后 call1最后 call2但它只是得到 call1、call2、call3。
我错过了什么让这些并行执行?

最佳答案

如果您为每个范围创建一个新范围,它们将并行启动:

suspend fun call1() = CoroutineScope(Dispatchers.IO).launch {
Log.d(TAG, "Call 1 started")
delay(2000)
Log.d(TAG, "Call 1 fiished")
}
更新:
虽然上述解决方案并行工作,但您无法跟踪可能导致执行泄漏的协程。为了保持结构并发,最好按照以下方式进行:
suspend fun call1() = withContext(Dispatchers.IO) {
Log.d(TAG, "Call 1 started")
delay(2000)
Log.d(TAG, "Call 1 fiished")
}

suspend fun call2() = withContext(Dispatchers.IO) {
Log.d(TAG, "Call 2 started")
delay(5000)
Log.d(TAG, "Call 2 finished")
}

suspend fun call3() = withContext(Dispatchers.IO) {
Log.d(TAG, "Call 3 started")
delay(1000)
Log.d(TAG, "Call 3 finished")
}
进而:
override suspend fun doWork(): Result{
setForeground(createForegroundInfo())

coroutineScope {
launch { call1() }
launch { call2() }
launch { call3() }
}
Log.d(TAG, "After all finishings")

return Result.success()
}

关于android - 协程没有并行运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63812589/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com