是否有像 ThreadPoolExecutor 这样创建新线程的协程上下文?
Is there a context for corutines that creates new threads up to a limit like a ThreadPoolExecutor?
我想让我的应用程序在收到更多请求时自动扩展一些,但我也想使用 Kotlin 提供的非阻塞协程。
查看文档似乎从 stdlib 获取上下文的唯一方法是使用 newSingleThreadContext
or newFixedThreadPoolContext
both creating instances of ThreadPoolDispacher
但似乎就是这样。
有没有一种方法可以使行为类似于 java 中的 ThreadPoolExecutor,如果当前没有线程可以在 Kotlin 中的 CoroutineContext 给定限制之前启动新线程?这甚至是处理协程的正确方法吗?
您可以将任何 Executor
变成协程上下文:
val MyContext = myExecutor.asCoroutineDispatcher()
Is this even the right way to thing about Coroutines?
这更多地取决于您使用协程执行的操作,而不是您使用的线程池类型。
我正在我的应用程序中使用缓存线程池,正如您所描述的那样。这是一个 Android 应用程序,因此保持苗条很重要。我使用线程池来阻止网络操作和 CPU-intensive 我必须在 GUI 线程之外完成的工作。在这样的用例中,您不会 launch (MyThreadPool)
您的协程,而是 launch(UI)
然后 withContext(MyThreadPool) { heavyWork }
.
我想让我的应用程序在收到更多请求时自动扩展一些,但我也想使用 Kotlin 提供的非阻塞协程。
查看文档似乎从 stdlib 获取上下文的唯一方法是使用 newSingleThreadContext
or newFixedThreadPoolContext
both creating instances of ThreadPoolDispacher
但似乎就是这样。
有没有一种方法可以使行为类似于 java 中的 ThreadPoolExecutor,如果当前没有线程可以在 Kotlin 中的 CoroutineContext 给定限制之前启动新线程?这甚至是处理协程的正确方法吗?
您可以将任何 Executor
变成协程上下文:
val MyContext = myExecutor.asCoroutineDispatcher()
Is this even the right way to thing about Coroutines?
这更多地取决于您使用协程执行的操作,而不是您使用的线程池类型。
我正在我的应用程序中使用缓存线程池,正如您所描述的那样。这是一个 Android 应用程序,因此保持苗条很重要。我使用线程池来阻止网络操作和 CPU-intensive 我必须在 GUI 线程之外完成的工作。在这样的用例中,您不会 launch (MyThreadPool)
您的协程,而是 launch(UI)
然后 withContext(MyThreadPool) { heavyWork }
.