Getting Started

Add the namespace reference

C#
using CI.TaskParallel;

Thread safety

Unity gameobjects cannot be updated from background threads, if you need to modify one then it should be done using one of the RunOnUIThread methods

Creating and running UnityTasks

That doesn't return a value

C#
var unityTask = new UnityTask(() => { // Do some work on a background thread }); unityTask.Start(); // This can be simplified using the static Run method var unityTask = UnityTask.Run(() => { // Do some work on a background thread });

That returns a value

C#
var unityTask = new UnityTask<int>(() => { // Do some work on a background thread and then return a value return 0; }); unityTask.Start(); // This can be simplified using the static Run method var unityTask = UnityTask.Run(() => { // Do some work on a background thread and then return a value return 0; });

Integrating with the UI thread

Unity gameobjects cannot be interacted with from background threads, so we must run code that interacts with them on the UI thread. A continuation can be used which takes the result of the previous UnityTask (if there was one) and then runs the following action on the UI thread

C#
UnityTask.Run(() => { // Do some work on a background thread and then return a value which will be passed to the continuation return 0; }).ContinueOnUIThread(t => { // Update a gameobject with the result of the previous UnityTask ResultText.text = "The result is: " + t.Result.ToString(); });

The static RunOnUIThread method can also be used

C#
UnityTask.RunOnUIThread(() => { // Update a gameobject });

Chaining UnityTasks

It's possible to chain multiple UnityTasks together with the result of the previous being passed to the next

C#
UnityTask.Run(() => { // Do some work on a background thread and then return a value return 0; }).ContinueWith((t) => { // Do some more work on another background thread and then return a value return t.Result + 1; });

Waiting for UnityTasks to complete

Each UnityTask instance has a "wait" function which will block the calling thread until it completes

C#
var unityTask = UnityTask.Run(() => { // Do some work on a background thread and then return a value return 0; }); unityTask.Wait();

There is also a static "WaitAll" to wait for multiple UnityTasks

C#
var t1 = UnityTask.Run(() => { // Do some work on a background thread }); var t2 = UnityTask.Run(() => { // Do some work on a background thread }); UnityTask.WaitAll(t1, t2);

If you don't want to block the calling thread then use "WhenAll" which raises a callback on the UI thread when all the supplied UnityTasks have completed

C#
var t1 = UnityTask.Run(() => { // Do some work on a background thread }); var t2 = UnityTask.Run(() => { // Do some work on a background thread }); UnityTask.WhenAll(() => { // Raised when all the supplied UnityTasks have completed }, t1, t2);