当suspended在主线程上运行时,我对协同线的内部工作很好奇。真正的问题是如何记录suspended函数,它是主线程上的协同线。到底是在哪里执行的?它是一个虚拟线程吗?
发布于 2019-04-04 04:11:32
如果您正在讨论记录coroutine名称:
你可以通过
launch(CoroutineName("My-Coroutine"))VM选项中的-Dkotlinx.coroutines.debug。

然后您可以在logcat中看到@My-Coroutine。
在编辑配置更改后,尝试下面的代码:
fun main() = runBlocking {
println(" 'runBlocking': I'm working in thread ${Thread.currentThread().name}")
val job = launch(CoroutineName("my-custom-name")) {
println(" 'runBlocking': I'm working in thread ${Thread.currentThread().name}")
}
job.join()}结果:

发布于 2020-09-19 03:06:12
其他的答案不是直接回答“如何在科特林得到一个协同线的名字?”,相反,他们建议如何命名一个协同线。
如果在协同线中,则可以使用currentCoroutineContext()[CoroutineName]检索名称。
如果在协同线之外,没有直接的方法可以使用对Job或Deferred的引用来检索名称(太糟糕了)。然而,有一个反射黑客可以使用。当然,通常的警告是附加的,即没有类型安全和侵入可能随时改变的内部API。
@Suppress("UNCHECKED_CAST")
val nameString = AbstractCoroutine::class.memberFunctions
.single { it.name == "nameString" } as Function1<AbstractCoroutine<*>, String>
val name = nameString(job as AbstractCoroutine<*>)
.replace("\"", "")
.takeWhile { it != '#' }包含此代码的方法/函数必须标记为@InternalCoroutinesApi。
发布于 2020-05-17 10:57:34
您可以在创建coroutine时使用CoroutineName(name:String)方法给coroutine命名:
repeat(5) {
GlobalScope.launch(CoroutineName("$it")) {
displayGreetingsFor(it)
}
}要检索coroutine的名称,请使用coroutineContext[CoroutineName.Key],如下所示:
private suspend fun displayGreetingsFor(i: Int) {
delay(100)
println(
" ${coroutineContext[CoroutineName.Key]} is executing on thread : ${Thread.currentThread().name}"
)
}这将在控制台上打印以下操作/p:
CoroutineName(0) is executing on thread : DefaultDispatcher-worker-3
CoroutineName(1) is executing on thread : DefaultDispatcher-worker-2
CoroutineName(2) is executing on thread : DefaultDispatcher-worker-8
CoroutineName(3) is executing on thread : DefaultDispatcher-worker-6
CoroutineName(4) is executing on thread : DefaultDispatcher-worker-5https://stackoverflow.com/questions/54319799
复制相似问题