美文网首页
协程-超时

协程-超时

作者: yunhen | 来源:发表于2024-04-16 13:15 被阅读0次
    fun testTimeout(timeMillis:Long,sleepTime :Long){
        val scope = MainScope()
        val ceh = CoroutineExceptionHandler { _, throwable ->
            when(throwable){
                is CancellationException ->{
                    Log.e("testTimeout"," CancellationException ")
                }
                else -> {
                    Log.e("testTimeout","throwable${throwable.message}")
                }
            }
    
    
        }
        scope.launch(ceh) {
            withContext(Dispatchers.IO){
                val s = withTimeoutOrNull(timeMillis){
                    return@withTimeoutOrNull suspendCancellableCoroutine<Boolean> {continuation ->
                        Log.e("suspendCancellableCoroutine"," 1 ")
                        SystemClock.sleep(sleepTime)
                        if (continuation.isActive)
                            continuation.resume(true)
                        else
                            continuation.cancel()
                        Log.e("suspendCancellableCoroutine"," 2 ")
    
                    }
                }
    
                when(s){
                    null ->{
                        Log.e(MainActivity.TAG,"超时了!")
                    }
                    true ->{Log.e(MainActivity.TAG,"没超时 true")}
                    else ->{Log.e(MainActivity.TAG,"超时? else ")}
                }
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:协程-超时

          本文链接:https://www.haomeiwen.com/subject/lswqxjtx.html