Kotlin 设置和获取协程名称

编程入门 行业动态 更新时间:2024-10-18 16:40:03

Kotlin 设置和获取协程<a href=https://www.elefans.com/category/jswz/34/1771109.html style=名称"/>

Kotlin 设置和获取协程名称

1,设置写成名称

创建协程作用域是或者创建协程是有个上下文参数(context: CoroutineContext)

创建协程作用域

CoroutineScope(Dispatchers.IO + CoroutineName("协程A"))//Dispatchers.IO根据实际情况设置可有可无

源码:

public fun CoroutineScope(context: CoroutineContext): CoroutineScope = ContextScope(if (context[Job] != null) context else context + Job())

创建协程的launch函数

GlobalScope.launch(Dispatchers.IO + CoroutineName("协程A")){//Dispatchers.IO根据实际情况设置可有可无, }

源码

public fun CoroutineScope.launch( context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> Unit )//注意函数前两个参数有默认值

由于CoroutineContext重写了+号,所以创建协程作用域或者创建协程的时候可以通过 Dispatchers.IO + CoroutineName("协程A")为函数context: CoroutineContext参数传递值;

2,获取协程名称
CoroutineScope(Dispatchers.IO + CoroutineName("协程A")).launch { Log.d(TAG, "当前线程和协程1: ${Thread.currentThread().name} + ${coroutineContext[CoroutineName]?.name}") runBlocking(CoroutineName("协程B")){ //runBlocking阻塞协程所在的线程2秒,因为此协程作用域内代码需要2秒才能执行完成 Log.d(TAG, "当前线程和协程: ${Thread.currentThread().name} ${coroutineContext[CoroutineName]?.name}") delay(1000.times(2)) //挂起函数,非阻塞式,挂起当前协程2秒 } Log.d(TAG,"当前线程和协程2:${Thread.currentThread().name} + ${coroutineContext[CoroutineName]?.name}") 
}

在协程内部调用如下API即可获取到协程名称

coroutineContext[CoroutineName]?.name

更多推荐

Kotlin 设置和获取协程名称

本文发布于:2023-12-07 13:19:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1671299.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:名称   Kotlin

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!