Search code examples
c#unity-game-engineserializationsavebinaryformatter

Checking if Binary Formatter's Serialize has finished


Is it possible to check if a binary formatter's Serialize() has finished writing to a file? I'm trying to make a save/load system in Unity and have decided to use a binary formatter but i'm not sure how to check if the serialization is complete. I wouldn't want the player to quit the game while the game is still loading and ideally would like to notify the player when the saving (serialization) is complete before they can proceed.

In case some code is needed:

    BinaryFormatter binaryFormatter = new BinaryFormatter();
    FileStream fileStream = new FileStream(Application.persistentDataPath + "/player.sav", FileMode.Create);

    PlayerData playerData = new PlayerData(player);
    binaryFormatter.Serialize(fileStream, playerData);
    fileStream.Close();

Solution

  • What we do at my company, is any time we write to disk, we write to a temporary location, and only when the full operation is complete we then do a File Move / Replace operation.

    This is the safest and simplest thing to implement. If the user quits and writing is still in progress, nothing gets broken.

    Also if there is any exceptions during the write process, nothing gets corrupted.