Home > Net >  await Task.Delay(1000); causing crashes - Unity C#
await Task.Delay(1000); causing crashes - Unity C#

Time:05-06

Main Issue: Unsure of what's happening in the background, but apparently whenever the line await Task.Delay(1000); is called Unity would turn unresponsive/freezes up.

Error msg: Tried checking callbacks from unity's profiler, but whenever the line in question were triggered unity would instantly turn unresponsive and not allowing any interaction (no callbacks/error messages were given out either).

Goal: The goal here is to simply call tryActivities[0] then, await for 1 second and then return true, and prints "Fished successfully!", without any crashing.

Suspicions: A suspicion I have is that the line tryActivities.Add(new Func<bool>(() => fs(currentSlot.basicData.typeID).Result)); need some sort of await? Though I'm also unsure of how to implement that either.

Inventory inventory; (Inventory.cs)

    List<Func<bool>> tryActivities = new List<Func<bool>>();
    public delegate Task<bool> Fish(int ID); Fish fs;

    void Start()
    {
        fs = new Fish(activities.Fish);
        tryActivities.Add(new Func<bool>(() => fs(currentSlot.basicData.typeID).Result));//await? how?
    }

    public void Interact()//called when a button is pressed
    {
        if (TryPlaceOrUse()) print("Fished successfully!");
        else print("Fishing failed");
    }

    bool TryPlaceOrUse()
    {
        if (tryActivities[(int)currentSlot.basicData.myActivity]())//tryActivities[0] 
        return true;
        return false;
    }

Activities activities; (Activities.cs)

    public async Task<bool> Fish(int ID)
    {
        await Task.Delay(1000);//crashes here
        return true;
    }

CodePudding user response:

This might do what you want. This is how you'd use a list of async Funcs, which is really just a list of Funcs that return Tasks of bool.

public class Program
{
    public delegate Task<bool> Fish(int ID);
    Fish fs;
    List<Func<Task<bool>>> tryActivities = new List<Func<Task<bool>>>();

    public async static Task Main()
    {
        Console.WriteLine("Hello, World!");

        Program program = new Program();

        program.Start();

        await program.Interact();
    }

    void Start()
    {
        fs = new Fish(Activities.Fish);
        tryActivities.Add(new Func<Task<bool>>(async () => await fs(4)));//await? how? like this :)
    }

    public async Task Interact() //called when a button is pressed
    {
        if (await TryPlaceOrUse())
            Console.WriteLine("Fished successfully!");
        else
            Console.WriteLine("Fishing failed");
    }

    async Task<bool> TryPlaceOrUse()
    {
        if (await tryActivities[0]()) //tryActivities[0] 
            return true;
        return false;
    }
}

public class Activities
{
    public static async Task<bool> Fish(int ID)
    {
        await Task.Delay(1000);//does not crash here
        return true;
    }
}
  • Related