Using Tasks with Coroutines

Although the Unity API is not thread safe, that does not mean you can’t use threading and other asynchronous programming techniques.

One of those is using Tasks in combination with Coroutines.

Firstly, it is important to point out Threads and Tasks are not the same. You can read about the differences over on Stack Overflow. Tasks are a nice way of doing asynchronous programming without the over head of creating and managing the OS-level threads.

We can use tasks really nicely with coroutines and also local functions.

Say we want to wait on some work done by some tasks in a coroutine. You can fire up tasks and then use WaitUntil in a corutine:

private IEnumerator CoroutineWithTasks()
    Task task1 = Task.Factory.StartNew(SomeWork1);
    Task task2 = Task.Factory.StartNew(SomeWork2);
    bool TasksFinished()
        bool task1Complete = task1.IsCompleted && task1.Status == 
        bool task2Complete  = task2.IsCompleted && task2.Status == 
    var waitUntil = new WaitUntil(TasksFinished);
    yield return waitUntil;

And it is as simple as that!

It is worth reiterating, the Unity API is not thread safe, so if you are going to do work in Tasks, it is worth doing it on non-Unity API work.