协程之取消和超时 Coroutines: Cancellation and Timeouts

官方原文链接:https://kotlinlang.org/docs/reference/coroutines/cancellation-and-timeouts.html

重点:每一个协程都会返回一个job实例

  1. 取消一个协程
//方法一
job.cancel()
job.join()
//方法二
job.cancelAndJoin()
  1. 使用 NonCancellable 令一个协程不可取消
launch(NonCancelable){
    ...
}
withContext(NonCancellable){
    ...
}

实例代码

import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        try {
            repeat(1000) { i ->
                println("job: I'm sleeping $i ...")
                delay(500L)
            }
        } finally {
            withContext(NonCancellable) {
                println("job: I'm running finally")
                delay(1000L)
                println("job: And I've just delayed for 1 sec because I'm non-cancellable")
            }
        }
    }
    delay(1300L) // delay a bit
    println("main: I'm tired of waiting!")
    job.cancelAndJoin() // cancels the job and waits for its completion
    println("main: Now I can quit.")    
}

运行结果

job: I'm sleeping 0 ...
job: I'm sleeping 1 ...
job: I'm sleeping 2 ...
main: I'm tired of waiting!
job: I'm running finally
job: And I've just delayed for 1 sec because I'm non-cancellable
main: Now I can quit.

  1. 异常处理
    当一个协程被取消时,会触发 CancellationException异常

在finally代码块关闭资源

import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        try {
            repeat(1000) { i ->
                println("job: I'm sleeping $i ...")
                delay(500L)
            }
        } finally {
            println("job: I'm running finally")
        }
    }
    delay(1300L) // delay a bit
    println("main: I'm tired of waiting!")
    job.cancelAndJoin() // cancels the job and waits for its completion
    println("main: Now I can quit.")    
}

运行结果

job: I'm sleeping 0 ...
job: I'm sleeping 1 ...
job: I'm sleeping 2 ...
main: I'm tired of waiting!
job: I'm running finally
main: Now I can quit.

  1. 设置超时及返回null
    超时:
import kotlinx.coroutines.*

fun main() = runBlocking {
    withTimeout(1300L) {
        repeat(1000) { i ->
            println("I'm sleeping $i ...")
            delay(500L)
        }
    }
}

I'm sleeping 0 ...
I'm sleeping 1 ...
I'm sleeping 2 ...
Exception in thread "main" kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 1300 ms

返回null:

import kotlinx.coroutines.*

fun main() = runBlocking {
    val result = withTimeoutOrNull(1300L) {
        repeat(1000) { i ->
            println("I'm sleeping $i ...")
            delay(500L)
        }
        "Done" // will get cancelled before it produces this result
    }
    println("Result is $result")
}

I'm sleeping 0 ...
I'm sleeping 1 ...
I'm sleeping 2 ...
Result is null

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 协程通过替代回调(callback)来简化异步代码。 协程的执行其实是断断续续的: 执行一段, 挂起来, 再执行一...
    凌烟醉卧阅读 3,445评论 0 1
  • 首发于公众号: DSGtalk1989 30.协程取消与超时 如何取消我们需要的取消上文中出现了cancel方法来...
    super_shanks阅读 3,292评论 1 1
  • kotlin这个夏天java最有竞争力的语言。关于它的语法糖在这就不一一阐述了,毕竟它能甜死你。先说说什么是协程吧...
    null_zhou阅读 4,027评论 3 7
  • 说是写作有点过了,仅仅是用英语记录当天的所思所感所想,只有3、5句话。但记得有人说过:你想要去到哪里,就从哪里开始...
    搬布阅读 884评论 0 5
  • 今天在出地铁口的时候,看到一个一老一少走在向上的阶梯上。看着小孩那么可爱就多看了两眼突然发现了一个有趣的事。 只见...
    痛惜阅读 332评论 0 0