use-casecoroutine

What are use cases for coroutines?


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?


Solution

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

    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).

    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.