协程的用例是什么? [英] What are use-cases for a coroutine?
问题描述
协程的概念听起来很有趣,但我不知道是否可以在实际的生产环境中有意义吗?协程的用例是什么,可以像其他方法一样更优雅,更简单或更有效地解决?
The concept of a coroutine sounds very interesting, but I don't know, if it makes sense in a real productive environment? What are use-cases for coroutines, that can be solved more elegant, simpler or more efficient as with other methods?
推荐答案
True协程需要您工具的支持-它们需要由编译器实现并由基础框架提供支持。
True coroutines require support from your tooling - they need to be implemented by the compiler and supported by the underlying framework.
一个协程实例的真实示例是收益回报 C#2.0中提供的关键字,它使您可以编写一个返回多个值以进行循环的方法。
One real world example of Coroutines is found with the "yield return" keyword provided in C# 2.0, which allows you to write a method that returns multiple values for looping.
但是,收益回报确实有局限性-该实现使用助手类来捕获状态,并且仅支持特定情况下的协程作为生成器(迭代器)
The "yield return" does have limitations, however - the implementation uses a helper class to capture state, and it only supports a specific case of coroutine as generator (iterator).
在更一般的情况下,协程的优点是它们使某些基于状态的计算更易于表达和易于理解-实现状态机因为一组协程比更常见的方法更优雅。但是,这样做需要C#或Java中尚不存在的支持和工具。
In the more general case, the advantage of Coroutines is that they make certain state based computations much easier to express and easier to understand - implementing a state machine as a set of coroutines can be more elegant than more common approaches. But, doing this requires support and tooling that doesn't yet exist in C# or Java.
这篇关于协程的用例是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!