统一(C#) – > Kotlin < – 协程

我正在试验Kotlin第一次,会喜欢一些帮助。

下面的代码是什么暂停执行当前函数而不休眠正在执行的线程。 暂停是基于提供的时间量。 该函数通过使用C#语言的协程支持来工作。 (这种支持最近也被添加到Kotlin!)

统一的例子

void Start() { print("Starting " + Time.time); StartCoroutine(WaitAndPrint(2.0F)); print("Before WaitAndPrint Finishes " + Time.time); } IEnumerator WaitAndPrint(float waitTime) { yield return new WaitForSeconds(waitTime); print("WaitAndPrint " + Time.time); } 

我一直无法弄清楚如何在Kotlin做类似的事情。 有人能帮助我指引正确的方向吗? 如果我在发布答案之前弄明白,我会更新我的帖子。

提前致谢!

请记住,协程是Kotlin 1.1的一部分,它仍在EAP(早期访问预览)中。 虽然我个人已经取得了巨大的成功,但API还不稳定,你不应该依赖它来生产。 另外,当Kotlin 1.1完成时,这个答案可能会过时。

  1. 如果您还没有,请按照本博客文章底部的说明将您的项目和IDE升级到最新的Kotlin 1.1 EAP里程碑(撰写本文时为M04)。
  2. 查找或写一个功能,将做你想做的。
    • kotlinx.coroutines有不少,但在这种情况下不是你要找的那个。
    • 幸运的是,写出一个非阻塞睡眠很容易 :

 private val executor = Executors.newSingleThreadScheduledExecutor { Thread(it, "sleep-thread").apply { isDaemon = true } } suspend fun sleep(millis: Long): Unit = suspendCoroutine { c -> executor.schedule({ c.resume(Unit) }, millis, TimeUnit.MILLISECONDS) } 

有一些重要的注意事项要注意。 与.NET相比,所有可挂起的方法都可以通过某个共享中央池进行处理(我甚至不知道在哪里,说实话),上面链接/显示的睡眠方法示例将运行执行程序池中的所有工作你指定。 上面链接的sleep方法示例使用单个线程,这意味着在sleep之后发生的所有工作都将由单个线程处理。 这可能不足以满足您的使用情况。

如果您对Kotlin协程的细节还有其他疑问,我强烈建议加入kotlinlang松弛中的#coroutines通道。 有关加入的详情,请参阅此处 。

这几乎是使用kotlix.coroutines库将C#Unity代码逐行转换为Kotlin协同程序:

 fun main(args: Array<String>) { println("Starting " + Instant.now()) launch(CommonPool) { waitAndPrint(2.0f) } println("Before waitAndPrint Finishes " + Instant.now()) // Kotlin coroutines are like daemon threads, so we have to keep the main thread around Thread.sleep(3000) } suspend fun waitAndPrint(waitTime: Float) { delay((waitTime * 1000).toLong()) // convert it to integer number of milliseconds println("waitAndPrint " + Instant.now()) } 

您可以通过示例中的kotlinx.coroutines指南了解更多信息,该示例中有更多示例,显示了Kotlin协同程序超出非阻塞睡眠的各种可用功能。