如果 kotlin 协程花费的时间超过一定时间,我想取消它。
这就是我正在做的事情:
GlobalScope.launch(Dispatchers.Main) {
val userOne = async(Dispatchers.IO) { Page_Load_Times() }.await()
Log.d("Tag", "Long Running task: $userOne")
}
suspend fun Page_Load_Times(): String? {
val startTime: Long = 0
var endTime: Long = 0
delay(5000) // if it is greater a certain time, eg 1000, I want to cancel the thread and return
return "Hey there"
}
如果kotlin协程运行时间超过一定时间,如何取消?
最佳答案
有内置的暂停函数: withTimeout
和 withTimeoutOrNull
.
只需在指定的超时时间内调用它:
GlobalScope.launch(Dispatchers.Main) {
val userOne = withContext(Dispatchers.IO) {
withTimeoutOrNull(5000) { Page_Load_Times() }
}
Log.d("Tag", "Long Running task: $userOne")
}
如果超时,您的userOne
将变为null
。
关于android - kotlin协程耗时超过一定时间如何取消?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64157169/