协程的用例是什么? [英] What are use cases for coroutines?

查看:81
本文介绍了协程的用例是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

协程的概念听起来很有趣,但我不知道是否在实际的生产环境中有意义吗?协程的用例是什么?协程的实现比其他方法更优雅,更简单或更有效?

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, where the coroutine implementation is more elegant, simpler or more efficient than other methods?

推荐答案

真正的协程需要语言支持.它们需要由编译器实现并得到基础框架的支持.

True coroutines require language support. They need to be implemented by the compiler and supported by the underlying framework.

协程的一种受语言支持的实现是C#2.0 关键字,它使您可以编写一种返回多个值以进行循环的方法.

One language-supported implementation of coroutines is the C# 2.0 yield return keyword, 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 the specific case of a coroutine as a generator (iterator).

在更一般的情况下,协程的一个优点是它们使某些基于状态的计算更易于表达和理解.例如,将状态机作为一组协程来实现可能比其他实现更优雅.但是,这样做需要C#或Java中尚不存在的语言支持.

In a more general case, an advantage of coroutines is that they make certain state-based computations easier to express and easier to understand. For example, implementing a state machine as a set of coroutines can be more elegant than other implementations. But doing this requires language support that doesn't yet exist in C# or Java.

这篇关于协程的用例是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆