将Coroutine调度员的任务转移到另一个调度员

发布于 2025-02-09 01:25:47 字数 59 浏览 1 评论 0原文

我的问题很简单,给定调度程序1,如何将调度器1的任务传输到名为Dispatcher 2的另一个调度程序?

My question is simple, given Dispatcher 1, how would you transfer Dispatcher 1's tasks to another Dispatcher named Dispatcher 2?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怀里藏娇 2025-02-16 01:25:47

不确定传输是什么意思,但是是的,您可以在线程之间跳跃。您可以在coroutine内使用with context线程之间切换。像这样:

val customContext = newSingleThreadContext("CustomContext")

runBlocking(Dispatchers.Default) {
    // Started in DefaultDispatcher
    withContext(customContext) {
        // Working in CustomContext
    }
    // Back to DefaultDispatcher
}
runBlocking(Dispatchers.Unconfined) {
    // Started in main thread
    withContext(Dispatchers.Default) {
        // Working in DefaultDispatcher
    }
    // Back to main thread
}

Not sure what transfer would mean but yes you can jump between threads. You can use withContext within a coroutine to switch between threads. Like so:

val customContext = newSingleThreadContext("CustomContext")

runBlocking(Dispatchers.Default) {
    // Started in DefaultDispatcher
    withContext(customContext) {
        // Working in CustomContext
    }
    // Back to DefaultDispatcher
}
runBlocking(Dispatchers.Unconfined) {
    // Started in main thread
    withContext(Dispatchers.Default) {
        // Working in DefaultDispatcher
    }
    // Back to main thread
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文