What are use-cases for a coroutine?

前端 未结 7 1846
你的背包
你的背包 2021-01-30 12:46

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

相关标签:
7条回答
  • 2021-01-30 13:44

    I know this is almost 5 years since the question was asked, but I am surprised no one mentioned the use case of games where coroutines are used a lot to essentially time slice a computation.

    To maintain a consistent frame rate in a game, lets say 60 fps, you have about 16.6ms to execute code in each frame. That includes physics simulation, input processing, drawing/painting.

    Lets say your method is executed in every frame. If your method takes a long time and ends up spanning multiple frames, you are going to stagger rest of the computation in the game loop which results in the user seeing "jank" (a sudden drop in frame rate).

    What coroutines let you do is somehow time slice this computation so that it runs a little bit in each frame.

    For that to happen, coroutines essentially allows the method to "yield" the computation back to the "caller" (in this case the game loop) so that the next time the method is called it resumes from where it left off.

    0 讨论(0)
提交回复
热议问题