Rust Wiki

Revision Difference

Coroutines#526563

<cat>Dev</cat>⤶ <title>Coroutines</title>⤶ ⤶ # Purpose⤶ ⤶ If you are already familiar with CSharp you may have heard of `Async` and `Task`. If so, skip ahead to `Coroutines Vs Async`.⤶ ⤶ # What is Async?⤶ ⤶ Lets say you need to make a web request to a remote server and it takes 1 second to respond. If you were use normal code your program would freeze for 1 full second.⤶ ⤶ This might not be a problem for some small program that run in the background but this is a massive problem for a game server where a server lag spike will anger players.⤶ ⤶ #What do we do?⤶ ⤶ Luckily there is a solution: `async` coding.⤶ ⤶ This allows you to run your code up to until web request and run the web request in the background.⤶ ⤶ While the web request is being processed the **code that doesn't not depend on the result of the web request** will continue to execute. ⤶ ⤶ When used correctly this prevents slow actions from freezing your program. Examples include:⤶ ⤶ * Web Requests⤶ * File Reads / Writes⤶ * Database Access⤶ * Etc⤶ ⤶ However, these is one 'gotcha' with `asnyc`...⤶ ⤶ ⤶ # Coroutines Vs Async⤶ ⤶ `Async` can run on a seperate thread when finished leading to unintentional multithreading⤶ ⤶ `Coroutines` always run on the main thread meaning it is safe and not extra considerations need to be taken⤶ ⤶ Beyond the usual dangers when multi-threading, Unity will throw an error if you try to use any unity functions from a seperate thread.⤶ ⤶ Coroutines are almost always required when splitting up work over multiple frames.⤶ ⤶ # How do I use them?⤶ ⤶