Scope 'Task' and 'Task<T>' to components

Created a Unity package for running ‘Task’ and ‘Task’ scoped to Unity components:
https://github.com/BastianBlokland/componenttask-unity

It gives them semantics that are much closer to Unity’s Coroutines (paused when the component is disabled and cancelled when the component is destroyed). This avoids all the ugly ‘if (!this) return;’ checks after every ‘await’ to guard against the component being destroyed while the task was running.

using System.Threading.Tasks;
using UnityEngine;

class MyClass : MonoBehaviour
{
    void Start()
    {
        this.StartTask(RunAsync);
    }

    async Task RunAsync()
    {
        while (true)
        {
            Debug.Log("Running...");
            await Task.Yield();
        }
    }
}

The above snipped would print ‘Running’ every frame, pause when disabling the component / gameobject and would stop when destroying the component / gameobject.

1 Like

This seems to solve my remaining issues for converting everything to async in Unity

Thinking of introducing ComponentTask into my project, but i’m looking for experiences with using this. Is there any pros&cons list anywhere?

We’ve been using it in our live game for a while and pretty happy so far.

One issue migrating previous async code was that we unintentionally had quite a bit of code that depended on the task running while the game-object is disabled, so it wasn’t plug and play. I’m considering adding some flag that you can give ‘StartTask’ that will allow the task to run even when the gameobject it is on is disabled (Even though i think its kind of bad practice as its not what you’re expecting if you’re used to coroutines).

What i personally love about the Task based async code is that it combines very well with multi-threading, as now code that needs to update some ui can ‘await’ a task that might be running on a thread-pool thread in a safe way.

Slightly unrelated but we’ve been using these helpers in our network layer to fire events from arbitrary threads but allow people to subscribe to those events on the Unity thread. So if you subscribe to the event from the Unity thread you will only be called back on the Unity thread. Makes it very easy to start moving logic to thread-pool tasks incrementally.

SynchronizedEvent

SynchronizedChannel

Great and confidence inspiring answer. I’m already using Tasks for most async code, but the cancellation token boilerplate is flow-killing and bug creating.

I will take a look at including this in my project, and will try to leave a review here.

The SynchronizedEvent is also nice! Will check it out.

Great to hear, really curious to hear how the integration goes.