Async: why is my task status always WaitingForActivation

In my application I have to load a large file and I don’t want it to freeze in the meantime so I’m trying to wrap my head around async/await. I’ve written some dummy code and it works as expected except for the fact that my task’s status always seems to be “WaitingForActivation”:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading.Tasks;

public class PointcloudAsyncTest : MonoBehaviour
{
    bool isLoading;
    bool isLoaded;
    TaskStatus taskStatus;
    void Awake()
    {
        Task taskReturn = LoadAsync();
        taskStatus = taskReturn.Status;
    }

    async Task LoadAsync()
    {
        isLoading = true;
        Debug.Log("Starting to load oh yeah!");
        await Task.Run(() => {          
                Task.Delay(15000).Wait();
            });
        isLoaded = true;
        isLoading = false;
    }
    // Update is called once per frame
    void Update()
    {
        Debug.Log("isLoading " + isLoading);
        Debug.Log("isLoaded " + isLoaded);
        Debug.Log("TaskStatus " + taskStatus);
    }
}

As expected, the LoadAsync method returns control to caller on await without blocking the main thread. After the delay ends isLoaded is set to true, and isLoading is set to false. However, the taskStatus is always WaitingForActivation. I guess I’m misunderstanding how to use the returns from async code, since here there are 2 async code segments (the LoadAsync function itself, and the Task.Run() code). How would I pass the TaskStatus from Task.Run() to the main thread?

8501594--1132106--upload_2022-10-10_14-31-2.png

Because TaskStatus is a value type and the Status property of the Task class just returns the current state. So you only read the state once in Awake (in line 15) and and store the current state in the variable taskStatus. Since you never read the status again, you will never get an updated state. You just grabbed the current state in Awake once right after you started your task. Instead of storing the TaskStatus, you probably want to store your “Task” object in a variable so you can actually read the current task status in Update.

Note: If your class (PointcloudAsyncTest) really is just responsible for loading the data, you may want to set enabled to false once the loading is done. That way Update does not run anymore once the loading is done. Though Update seems to be for debugging purposes only at the moment. So you have to decide dfor yourself.

1 Like

I got you! I thought there was some mechanism under the hood to update the status in real-time. It works now by setting a loadTask variable in the class’ scope, and reading it’s status in Update.