Save/Load Async using Task

hey, Trying to make async save and load functions.
How can i test these to see if they actually ran async?
Save:

private static async void SerializeData(BinaryFormatter bf)
    {
        isDoneAsync = false;
        await Task.Run(() =>
        {
            using (FileStream stream = File.Open(FILE_PATH, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                m_Data.isSaved = true;
                bf.Serialize(stream, m_Data);
            }
        });
        Debugger.Log("Saved Async");
        isDoneAsync = true;
    }

Load:

private static async void DeserializeData(BinaryFormatter bf)
    {
        isDoneAsync = false;
        await Task.Run(() =>
        {
            using (FileStream stream = new FileStream(FILE_PATH, FileMode.Open, FileAccess.Read))
            {
                m_Data = bf.Deserialize(stream) as T;
            }
        });
        Debugger.Log("Loaded Async");
        isDoneAsync = true;
    }
1 Like

Hmm apparently they don’t work, visual studio just skips the calls…
calling them like this:

private static bool DeserializeData(BinaryFormatter bf, bool async = false)
    {
        if (!File.Exists(FILE_PATH))
            return false;

        if(async)
        {
            DeserializeData(bf).Wait();
            return isDoneAsync;
        }
        else
        {
            using (FileStream stream = new FileStream(FILE_PATH, FileMode.Open, FileAccess.Read))
            {
                m_Data = bf.Deserialize(stream) as T;
            }
            return true;
        }
    }
1 Like

ok so just for others, i got it to work like this:
To Call it:

public static async Task<bool> SaveAsync()
    {
        if (saveData == null)
            saveData = await SerializationManager<SaveData>.LoadAsync();
        saveData.Data[DataIndex] = resortData;
        return await SerializationManager<SaveData>.SaveAsync(saveData);
    }

in my SerializationManager:

public static async Task<bool> SaveAsync(T data)
    {
        BinaryFormatter bf = new BinaryFormatter();
        Debugger.Log("File saved at: " + FILE_PATH);
        m_Data = data;
        return await SerializeDataAsync(bf);
    }
private static async Task<bool> SerializeDataAsync(BinaryFormatter bf)
    {
        await Task.Run(() =>
        {
            using (FileStream stream = File.Open(FILE_PATH, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                m_Data.isSaved = true;
                bf.Serialize(stream, m_Data);
            }
        });
        Debugger.Log("Saved Async");
        return true;
    }

so any method that wants to call async saving or loading needs to have the async keyword, and to get the return type use the await keyword.

4 Likes

Wow, it helped me a lot! Thanks man!

Thank you