Skip to content
ToanLB
Go back

Handling Scene Unloads During Async Operations: CancellationToken Architecture, Eliminating Zombie Tasks, and Preventing Memory Leaks in Unity

~14 min read
Handling Scene Unloads During Async Operations: CancellationToken Architecture, Eliminating Zombie Tasks, and Preventing Memory Leaks in Unity

In mid-to-large scale Unity projects, asynchronous resource loading is ubiquitous: dungeon loading screens streaming level prefabs, gacha banners downloading high-resolution textures from remote CDNs, or persistent save systems serializing multi-megabyte game states in background workers.

A classic player behavior in mobile games is impatience. While a loading spinner rotates on screen, the player decides to cancel, tapping the hardware back button or closing the modal window to return to the main lobby. When this happens, the active scene unloads or the UI GameObject is immediately destroyed.

Back when Coroutines dominated Unity development, this scenario rarely posed serious stability risks. Unity PlayerLoop naturally halted coroutines as soon as their host GameObject was destroyed. However, as production codebases modernized toward async/await patterns using C# Tasks, UniTask, or Unity 6 Awaitables, an insidious failure mode emerged: the GameObject vanishes from the scene, but the asynchronous task continues running silently in the background. Several seconds later, once the network payload finishes downloading, execution resumes right after the await keyword. The code attempts to assign a texture to a destroyed UI component, immediately triggering red console errors:

MissingReferenceException: The object of type 'Image' has been destroyed but you are still trying to access it.

Worse yet, if this asynchronous continuation mutates global state or updates an active player profile singleton, data from the abandoned level overwrites state in the newly loaded scene. In game engineering, this phenomenon is widely recognized as a Zombie Async Task.

Why do asynchronous state machines persist when GameObjects are destroyed, unlike native Coroutines? How does Unity dual-memory architecture behave between the C# Managed Heap and C++ Engine during scene unloads? And how can we build a leak-free cancellation architecture around CancellationToken?


1. Architectural Internals: Dual Memory and the Anatomy of Zombie Tasks

To establish an airtight cancellation strategy, we must first inspect the mechanical divergence between cooperative coroutines and C# asynchronous state machines.

flowchart LR
    subgraph SceneLifecycle["Scene & GameObject Lifecycle"]
        direction TB
        A["Player Taps Back"] --> B["SceneManager.UnloadSceneAsync"]
        B --> C["GameObject Destroyed"]
        C --> D["Native Pointer m_CachedPtr = null"]
    end

    subgraph AsyncExecution["Managed Heap Async Execution"]
        direction TB
        E["IAsyncStateMachine Boxed Instance"] --> F["Awaiting WebRequest / Task"]
        F --> G["Task Completes After 3 Seconds"]
        G --> H["Resumes Continuation After Await"]
    end

    subgraph MemoryConsequences["Unchecked Task Consequences"]
        direction TB
        I["MissingReferenceException"]
        K["RAM Leak via Closure GC Root"]
        L["Corrupted Global GameState"]
    end

    C -.->|"Fails to Cancel"| E
    H -->|"Invokes ICall via Null Pointer"| I
    H -->|"Anchors Abandoned Managed Shell"| K
    H -->|"Overwrites Active Singleton"| L

Cooperative Coroutine Teardown

When invoking StartCoroutine(), Unity instantiates an internal tracking object and registers it directly into the native execution list of the host MonoBehaviour inside the C++ engine.

During every frame of the PlayerLoop, Unity iterates through this active list and calls MoveNext() on each IEnumerator. When a GameObject is destroyed or its parent scene unloads, Unity purges these coroutine handles from the C++ update schedule. The coroutine terminates deterministically alongside its host GameObject without requiring manual developer intervention.

Decoupled C# State Machines

In stark contrast, async/await is a language feature implemented by the Roslyn compiler and the .NET runtime. It is entirely decoupled from Unity scene graph semantics:

  1. State Machine Generation: When compiling an async method, Roslyn transforms the method into a struct or class implementing IAsyncStateMachine.
  2. Heap Allocation and Boxing: When hitting an incomplete awaitable, the state machine is boxed onto the Managed Heap and registered with the active synchronization harness (SynchronizationContext, the .NET ThreadPool, or UniTask PlayerLoopRunner).
  3. Scene-Agnostic Lifetime: Because runtime GC roots anchor this state machine, it remains completely oblivious to whether the associated Unity GameObject is alive or destroyed.

Dual Memory Architecture and Null Reference Illusions

In Unity, every MonoBehaviour consists of two distinct halves:

When a scene unloads:

When the async task completes, the continuation executes statements like image.sprite = downloadedSprite. The C# wrapper executes an internal call (ICall) across the boundary, encounters a null native pointer, and immediately throws MissingReferenceException.

Silent Memory Leaks

The architectural damage extends far beyond cosmetic console errors:


2. Cancellation Architecture: From Manual Boilerplate to destroyCancellationToken

In standard .NET engineering, cooperative cancellation revolves around two core primitives: CancellationTokenSource (the coordinator) and CancellationToken (the lightweight listener struct).

flowchart LR
    subgraph Triggers["Cancellation Sources"]
        direction TB
        T1["MonoBehaviour.destroyCancellationToken"]
        T2["Timeout Token (e.g. 10 Seconds)"]
    end

    subgraph Coordinator["Linked CTS Coordinator"]
        direction TB
        M1["CreateLinkedTokenSource"]
        M2["Pass linkedToken Down Async Chain"]
        M3["Using Block Deterministic Dispose"]
    end

    subgraph SafeHandling["Graceful Resolution"]
        direction TB
        R1["OperationCanceledException"]
        R2["Catch Specifically for Silent Exit"]
        R3["Clean Up In-Flight Buffers & Handles"]
    end

    T1 -->|"Bind Host Lifecycle"| M1
    T2 -->|"Bind Network Deadline"| M1
    M1 --> M2
    M2 --> M3
    M2 -.->|"Triggers on Cancellation"| R1
    R1 --> R2
    R1 --> R3

Passing Tokens Across the Invocation Pipeline

To prevent zombie tasks, every asynchronous method handling I/O, network requests, or timing should accept a cancellation token parameter:

CancellationToken cancellationToken = default

This readonly struct carries an internal reference to its parent CancellationTokenSource. It must be forwarded downstream throughout the entire call graph: from presentation controllers down through domain services and network wrappers.

Pitfalls of Manual CancellationTokenSource Management

Prior to Unity 2022.2, developers routinely managed CTS lifetimes manually within individual components:

using System.Threading;
using UnityEngine;

public class ManualCancelDemo : MonoBehaviour
{
    private CancellationTokenSource _cts;

    private void Awake()
    {
        _cts = new CancellationTokenSource();
    }

    private void OnDestroy()
    {
        if (_cts != null)
        {
            _cts.Cancel();
            _cts.Dispose();
        }
    }
}

This pattern exhibits three notable shortcomings as projects scale:

  1. Repetitive Boilerplate: Hundreds of UI components duplicate identical allocation, cancellation, and disposal logic.
  2. Human Error: Under tight production deadlines, engineers frequently omit OnDestroy() teardown, allowing zombie tasks to resurface unnoticed.
  3. ObjectDisposedException Collisions: Calling _cts.Dispose() while downstream asynchronous operations are concurrently querying or registering callbacks against the token triggers unexpected runtime exceptions.

Native Integration: destroyCancellationToken in Unity 2022.2+ and Unity 6

Beginning in Unity 2022.2 LTS and refined in Unity 6, Unity introduced the native destroyCancellationToken property directly on MonoBehaviour.

When a GameObject is destroyed or its scene unloads, the native C++ engine automatically cancels this token immediately prior to invoking OnDestroy(). Developers can forward this.destroyCancellationToken directly into asynchronous workflows without manually managing a CancellationTokenSource:

using System.Threading.Tasks;
using UnityEngine;

public class NativeCancelDemo : MonoBehaviour
{
    public async Task LoadAssetAsync()
    {
        // Automatically cancels when the GameObject is destroyed
        await Task.Delay(2000, this.destroyCancellationToken);
    }
}

For teams leveraging UniTask, this.GetCancellationTokenOnDestroy() provides equivalent functionality across older Unity releases. UniTask also offers this.GetCancellationTokenOnDisable(), which cancels operations the moment a UI popup is hidden via SetActive(false).

Combining Lifecycle and Deadlines with Linked Tokens

In production environments, cancelling purely on destruction leaves an unaddressed vulnerability: network stalls. If a player connection drops packets and the server hangs, a loading spinner will rotate indefinitely if no timeout mechanism exists.

We resolve this by combining two distinct cancellation triggers: component destruction and an elapsed timeout threshold (e.g., 10 seconds).

We compose these conditions using CancellationTokenSource.CreateLinkedTokenSource:

using System;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;

public class LinkedTimeoutCancelDemo : MonoBehaviour
{
    private async Task FetchRemoteDataAsync(CancellationToken ct)
    {
        await Task.Delay(500, ct);
    }

    public async Task LoadWithTimeoutAsync(CancellationToken externalToken)
    {
        using var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
        using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(externalToken, timeoutCts.Token);

        // This operation terminates if externalToken cancels OR when 10 seconds elapse
        await FetchRemoteDataAsync(linkedCts.Token);
    }
}

Critical Memory Note: CreateLinkedTokenSource allocates a new CTS instance on the Managed Heap and registers internal delegate callbacks against both parent tokens. If you fail to release it via a using declaration or explicit Dispose() call inside a finally block, these registered delegates remain anchored in parent token callback lists, causing delegate memory leaks.


3. Exception Handling and Intermediate Resource Cleanup

When an in-flight asynchronous task receives a cancellation signal, the operation halts and throws OperationCanceledException (or its subclass TaskCanceledException). How our architecture intercepts this exception dictates production stability.

The Pitfall of Catch-All Blocks

A common anti-pattern during rapid development is wrapping async calls in generic try - catch (Exception ex) blocks followed by Debug.LogError(ex).

Consequently, whenever a player taps the back button during normal gameplay, the console logs an error. Automated monitoring suites such as Firebase Crashlytics or Sentry interpret these logs as production crashes, polluting telemetry metrics with thousands of false positives.

Proper Exception Triaging

Robust asynchronous error handling enforces two distinct tiers:

  1. Intercept OperationCanceledException Explicitly: Cancellation is an intentional control flow signal, not a software failure. This catch block should exit silently or run local cleanup without logging error telemetry.
  2. Intercept Real Exceptions Downstream: Subsequent catch (Exception ex) blocks capture genuine runtime failures such as JSON parsing errors or dropped TCP connections.
using System;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;

public class ExceptionHandlingDemo : MonoBehaviour
{
    private async Task LoadBigBundleAsync(CancellationToken ct)
    {
        await Task.Delay(100, ct);
    }

    private void UpdateUI() { }

    public async Task SafeLoadAsync(CancellationToken cancellationToken)
    {
        try
        {
            await LoadBigBundleAsync(cancellationToken);
            UpdateUI();
        }
        catch (OperationCanceledException)
        {
            // Intentional player exit: silent exit without error logging
        }
        catch (Exception ex)
        {
            // Genuine network or I/O failure: log for diagnostics
            Debug.LogError($"Asset load failed: {ex.Message}");
        }
    }
}

Zero-Allocation Cancellation via SuppressCancellationThrow in UniTask

In standard .NET runtime environments, throwing an exception incurs noticeable overhead: the runtime unwinds the call stack and allocates an Exception object on the Managed Heap. If an expansive scene unloads and cancels dozens of concurrent asset downloads simultaneously, multiple exceptions trigger an acute GC spike.

UniTask provides an elegant zero-allocation alternative via .SuppressCancellationThrow(). Instead of unwinding the stack with an exception, this extension method catches the cancellation internally and returns a value-tuple (bool isCanceled, T result). A clean if (isCanceled) return; check terminates execution linearly without generating garbage on the heap.

Releasing In-Flight Resources

When an operation cancels mid-stream, open handles must be released immediately:


4. Production Architecture: Safe Async Operation Runner

In a mobile Action RPG, the dungeon subsystem pre-loads monster configurations, loot tables, and spawn coordinates asynchronously from remote APIs and local storage. Players retain the freedom to tap Cancel or hit the hardware back button at any moment during loading. The production constraints require a 10-second timeout ceiling, silent cancellation on early exit without console spam, and zero state corruption if an abandoned level finishes downloading after the player returns to the lobby.

To decouple this coordination logic from Unity engine dependencies and facilitate automated testing, we encapsulate execution in a pure C# class named AsyncOperationRunner<T>, integrated with a scene component named DungeonDataLoaderComponent. In production projects, it is recommended to isolate AsyncOperationRunner<T> in a standalone Pure C# assembly definition (.asmdef) within your Domain layer, free from UnityEngine.dll dependencies to maximize reusability and optimize compilation times.

Production Implementation

using System;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;

// Execution status for asynchronous operations
public enum AsyncOperationStatus
{
    Success,
    Canceled,
    TimedOut,
    Failed
}

// Zero-allocation readonly result container
public readonly struct AsyncOperationResult<T>
{
    public readonly AsyncOperationStatus Status;
    public readonly T Value;
    public readonly Exception Error;

    public bool IsSuccess => Status == AsyncOperationStatus.Success;
    public bool IsCanceled => Status == AsyncOperationStatus.Canceled;
    public bool IsTimedOut => Status == AsyncOperationStatus.TimedOut;

    public AsyncOperationResult(AsyncOperationStatus status, T value, Exception error = null)
    {
        Status = status;
        Value = value;
        Error = error;
    }

    public static AsyncOperationResult<T> Succeeded(T value) =>
        new(AsyncOperationStatus.Success, value);

    public static AsyncOperationResult<T> Canceled() =>
        new(AsyncOperationStatus.Canceled, default);

    public static AsyncOperationResult<T> TimedOut() =>
        new(AsyncOperationStatus.TimedOut, default);

    public static AsyncOperationResult<T> Failed(Exception error) =>
        new(AsyncOperationStatus.Failed, default, error);
}

// Pure C# asynchronous operation coordinator with timeout and cancellation safety
public class AsyncOperationRunner<T>
{
    public async Task<AsyncOperationResult<T>> ExecuteAsync(
        Func<CancellationToken, Task<T>> operation,
        CancellationToken externalToken = default,
        TimeSpan timeout = default)
    {
        if (operation == null)
            throw new ArgumentNullException(nameof(operation));

        // When no timeout is specified, listen solely to externalToken
        if (timeout <= TimeSpan.Zero)
        {
            try
            {
                externalToken.ThrowIfCancellationRequested();
                T result = await operation(externalToken);
                return AsyncOperationResult<T>.Succeeded(result);
            }
            catch (OperationCanceledException)
            {
                return AsyncOperationResult<T>.Canceled();
            }
            catch (Exception ex)
            {
                return AsyncOperationResult<T>.Failed(ex);
            }
        }

        // Compose externalToken and timeoutToken via Linked CTS
        using var timeoutCts = new CancellationTokenSource(timeout);
        using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(externalToken, timeoutCts.Token);

        try
        {
            linkedCts.Token.ThrowIfCancellationRequested();
            T result = await operation(linkedCts.Token);
            return AsyncOperationResult<T>.Succeeded(result);
        }
        catch (OperationCanceledException)
        {
            // Disambiguate between external cancellation and timeout triggers
            if (externalToken.IsCancellationRequested)
            {
                return AsyncOperationResult<T>.Canceled();
            }

            if (timeoutCts.IsCancellationRequested)
            {
                return AsyncOperationResult<T>.TimedOut();
            }

            return AsyncOperationResult<T>.Canceled();
        }
        catch (Exception ex)
        {
            return AsyncOperationResult<T>.Failed(ex);
        }
    }
}

// Scene controller orchestrating asynchronous dungeon loading
public class DungeonDataLoaderComponent : MonoBehaviour
{
    [SerializeField] private float timeoutSeconds = 10f;

    private AsyncOperationRunner<string> _runner;
    private string _cachedDungeonData;
    private int _successfulLoadsCount;

    public string CachedDungeonData => _cachedDungeonData;
    public int SuccessfulLoadsCount => _successfulLoadsCount;

    private void Awake()
    {
        _runner = new AsyncOperationRunner<string>();
    }

    // Public initiation point for level loading
    public async Task<bool> RequestLoadDungeonAsync(Func<CancellationToken, Task<string>> dataFetcher, CancellationToken ct = default)
    {
        _runner ??= new AsyncOperationRunner<string>();

        // Link the host component lifecycle token with any external cancellation token
        using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(this.destroyCancellationToken, ct);

        // Execute safely with component lifecycle token and timeout budget
        var result = await _runner.ExecuteAsync(dataFetcher, linkedCts.Token, TimeSpan.FromSeconds(timeoutSeconds));

        if (result.IsSuccess)
        {
            _cachedDungeonData = result.Value;
            _successfulLoadsCount++;
            return true;
        }

        // On Canceled or TimedOut, bypass state updates to preserve scene integrity
        return false;
    }
}

Automated Verification via NUnit

To verify that AsyncOperationRunner accurately handles normal completions, player-initiated cancellations, timeout deadlines, and unexpected exceptions, we implement an automated test suite:

using System;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;

[TestFixture]
public class AsyncOperationRunnerTests
{
    [Test]
    public async Task ExecuteAsync_WhenCompletedNormally_ReturnsSuccessWithData()
    {
        var runner = new AsyncOperationRunner<string>();

        var result = await runner.ExecuteAsync(
            async ct =>
            {
                await Task.Yield();
                return "Dungeon_Floor_Boss_Data";
            },
            externalToken: CancellationToken.None,
            timeout: TimeSpan.FromSeconds(2));

        Assert.IsTrue(result.IsSuccess);
        Assert.AreEqual(AsyncOperationStatus.Success, result.Status);
        Assert.AreEqual("Dungeon_Floor_Boss_Data", result.Value);
        Assert.IsNull(result.Error);
    }

    [Test]
    public async Task ExecuteAsync_WhenExternalTokenCanceled_ReturnsCanceledStatus()
    {
        var runner = new AsyncOperationRunner<string>();
        using var externalCts = new CancellationTokenSource();

        // Signal cancellation before the asynchronous payload resolves
        externalCts.Cancel();

        var result = await runner.ExecuteAsync(
            async ct =>
            {
                await Task.Delay(200, ct);
                return "Should_Never_Return";
            },
            externalToken: externalCts.Token,
            timeout: TimeSpan.FromSeconds(2));

        Assert.IsTrue(result.IsCanceled);
        Assert.AreEqual(AsyncOperationStatus.Canceled, result.Status);
        Assert.IsNull(result.Value);
        Assert.IsNull(result.Error);
    }

    [Test]
    public async Task ExecuteAsync_WhenTimeoutOccurs_ReturnsTimedOutStatus()
    {
        var runner = new AsyncOperationRunner<int>();

        // Operation requests 500ms but timeout budget is constrained to 50ms
        var result = await runner.ExecuteAsync(
            async ct =>
            {
                await Task.Delay(500, ct);
                return 999;
            },
            externalToken: CancellationToken.None,
            timeout: TimeSpan.FromMilliseconds(50));

        Assert.IsTrue(result.IsTimedOut);
        Assert.AreEqual(AsyncOperationStatus.TimedOut, result.Status);
        Assert.AreEqual(0, result.Value);
    }

    [Test]
    public async Task ExecuteAsync_WhenOperationThrowsException_ReturnsFailedStatus()
    {
        var runner = new AsyncOperationRunner<string>();

        var result = await runner.ExecuteAsync(
            async ct =>
            {
                await Task.Yield();
                throw new InvalidOperationException("Corrupted JSON payload");
            },
            externalToken: CancellationToken.None,
            timeout: TimeSpan.FromSeconds(1));

        Assert.IsFalse(result.IsSuccess);
        Assert.AreEqual(AsyncOperationStatus.Failed, result.Status);
        Assert.IsNotNull(result.Error);
        Assert.IsInstanceOf<InvalidOperationException>(result.Error);
        Assert.AreEqual("Corrupted JSON payload", result.Error.Message);
    }
}

5. Architectural Trade-offs

Every cancellation approach balances implementation complexity against allocation overhead and safety guarantees. The matrix below synthesizes core technical trade-offs across common patterns:

Evaluation MetricManual CTS LifecycledestroyCancellationToken (Native)UniTask CancellationTokenLinked Token Source (With Timeout)
GC Allocation OverheadModerate due to manual CTS heap allocationMinimal because engine manages token internallyZero-Alloc when combined with SuppressCancellationAllocates heap instance for Linked CTS coordinator
Boilerplate BurdenHigh (manual allocation, Cancel, and Dispose)Zero boilerplate, pass instance token directlyMinimal, call direct extension methodRequires using block or try-finally for disposal
Stall Protection (Timeout)Requires custom timer or stopwatch logicNo built-in timeout, cancels strictly on DestroySupported via CancellationTokenSource.CancelAfterSlimNative, robust, and highly flexible
Library DependencyZero dependencies, standard .NETRequires Unity 2022.2 LTS or Unity 6Depends on external UniTask packageZero dependencies, standard .NET
Optimal Use CaseLegacy projects on older Unity releasesStandard UI tasks in Unity 2022.2+ and Unity 6Mobile projects with strict GC allocation budgetsCritical remote network requests needing timeout ceilings

6. Practical Takeaways for Asynchronous Unity Systems

Disciplined lifecycle management in asynchronous operations protects long-running game sessions from memory fragmentation and unpredictable state mutations.

Four principles summarize production best practices:

  1. Accept CancellationToken by Default: Ensure every asynchronous method accepting I/O, server queries, or delays includes CancellationToken cancellationToken = default. Forward tokens uniformly across layers so cancellation chains never sever unexpectedly.
  2. Leverage Native Lifecycle Tokens: When developing on Unity 2022.2+ or Unity 6, prioritize this.destroyCancellationToken. It clarifies intent and permanently eliminates forgotten OnDestroy() teardowns.
  3. Decouple Cancellation from Error Reporting: Intercept OperationCanceledException explicitly to ensure graceful early exits. A player navigating away from a screen is an intended interaction, not a critical runtime failure.
  4. Always Dispose Linked Token Sources: Whenever composing timeout thresholds via CreateLinkedTokenSource, enclose instances within using declarations to unregister event listeners, safeguarding the Managed Heap against delegate leaks.

Share this post:
Lương Bảo Toàn

Luong Bao Toan

I work in HMI Automotive and Game development, sharing knowledge, hands-on experience, and stories I find interesting throughout my journey.

Did this article bring you value?

If this article helped your work, or you simply enjoyed it and want to support me, you can

Buy me a coffee

Related Articles

Comments & Discussions

Powered by Giscus

Get New Posts via Email

Subscribe to stay updated and never miss new posts from me.

* No spam. You can unsubscribe at any time with a single click.