hey, Trying to make async save and load functions. How can i test these to see if they actually ran async? Save: Code (CSharp): 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: Code (CSharp): 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; }
Hmm apparently they don't work, visual studio just skips the calls... calling them like this: Code (CSharp): 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; } }
ok so just for others, i got it to work like this: To Call it: Code (CSharp): 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: Code (CSharp): 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.