作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的 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/
在我的设置中,我试图有一个界面 Table继承自 Map (因为它主要用作 map 的包装器)。两个类继承自 Table - 本地和全局。全局的将有一个可变的映射,而本地的将有一个只有本地条目的映射。
Rust Nomicon 有 an entire section on variance除了关于 Box 的这一小节,我或多或少地理解了这一点和 Vec在 T 上(共同)变体. Box and Vec
我是一名优秀的程序员,十分优秀!