简体   繁体   English

有没有办法在 Kotlin 协程范围内启动可运行的?

[英]Is there a way to launch a runnable within a Kotlin coroutine scope?

The context is that I need to work with some legacy Java code that uses the old world threading models.上下文是我需要使用一些使用旧世界线程模型的遗留 Java 代码。 Thread pool executors, schedulers and runnables and threads.线程池执行程序、调度程序以及可运行程序和线程。

However, my new code is all coroutine compatible.但是,我的新代码与所有协程兼容。

So, given a runnable所以,给定一个可运行的

val runnable = Runnable { 
    print("Hurray")
}

Is there a better way to run this runnable within a coroutine scope than the following which feels a little clumsy (you're really just going around the fact that you're trying to run a runnable and squeezing it in a coroutine)有没有比以下更好的方法在协程范围内运行这个 runnable 感觉有点笨拙(你真的只是绕过你试图运行一个 runnable 并在协程中挤压它的事实)

GlobalScope.launch(Dispatchers.IO) { runnable.run() }

Is there a way interoperably work with runnables and coroutines?有没有一种方法可以与 runnables 和协程互操作?

Given the entirety of your input in the question, this is all you need to execute the Runnable :鉴于您在问题中的全部输入,这就是执行Runnable所需的全部内容:

runnable.run()

Now, if you implicitly assume there is some long-lasting computation or blocking I/O behind that runnable, and you don't want to block the current thread, then you must dispatch it to a background thread pool, which is exactly the same you would have to do in Java.现在,如果您隐含地假设在可运行对象背后有一些持久计算或阻塞 I/O,并且您不想阻塞当前线程,那么您必须将其分派到后台线程池,这完全相同你必须用Java做。 In that case you would have to write what you call the "clumsy" idiom.在这种情况下,您将不得不编写您称之为“笨拙”的习语。

If your wish is to be able to just write runnable.run() and have Kotlin somehow, automagically, turn your blocking IO code into suspending, that is impossible for fundamental reasons.如果您希望能够只编写runnable.run()并让 Kotlin 以某种方式自动将阻塞 IO 代码转换为挂起,那么出于根本原因,这是不可能的。 The Java code in that case executes native system calls which block the calling thread and there is no way around that fact.在这种情况下,Java 代码执行阻止调用线程的本机系统调用,并且无法绕过这个事实。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM