最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

kotlin - Getting inconsistent results when using withTimeoutOrNull within small margins - Stack Overflow

programmeradmin6浏览0评论

Upon rerunning the following code, I am getting inconsistencies:

fun main(){
    runBlocking{
        withTimeoutOrNull(205){
            delay(200)
            println("Within Timeout")
        }
        delay(300)
        println("Outside")
    }
}

This appears to be the case within difference margins of 1-10 milliseconds. The console will sometimes printout both print statements but most often, the last println only gets displayed. Why is this happenning?

Upon rerunning the following code, I am getting inconsistencies:

fun main(){
    runBlocking{
        withTimeoutOrNull(205){
            delay(200)
            println("Within Timeout")
        }
        delay(300)
        println("Outside")
    }
}

This appears to be the case within difference margins of 1-10 milliseconds. The console will sometimes printout both print statements but most often, the last println only gets displayed. Why is this happenning?

Share Improve this question asked Mar 20 at 15:03 Ken KiarieKen Kiarie 1411 gold badge1 silver badge8 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

withTimeoutOrNull(timeMillis, block) cancels the block and returns null if the timeout (timeMillis) was exceeded.

delay(200) does not guarantee that delay will be exactly 200 ms, it guarantees that the delay is at least 200 ms.
So in case the actual delay is larger 205 ms, withTimeoutOrNull(205) cancels the passed code block and println("Within Timeout") is not executed.

From the delay's doc:

Delays coroutine for at least the given time without blocking a thread and resumes it after a specified time.

From the withTimeoutOrNull's doc:

The code that is executing inside the block is cancelled on timeout and the active or next invocation of cancellable suspending function inside the block throws a TimeoutCancellationException.

发布评论

评论列表(0)

  1. 暂无评论