Course contentsShow
← Unity Game Development
Lesson 756 of 82811. Performance and Data PersistenceFree lesson

Managing Asynchronous File I/O Operations

Learners will implement non-blocking file operations to prevent frame rate drops and application hangs during heavy save or load sequences.

In this lesson, you will learn how to leverage asynchronous file I/O to perform data persistence without causing the dreaded "hitch" or frame drop during gameplay.

When you perform standard file operations using System.IO (like File.WriteAllText or File.ReadAllBytes), the main thread halts until the storage device completes the transaction. On mobile devices or consoles with slower disk speeds, large save files can cause the game to freeze for several milliseconds, which is visually jarring.

To prevent this, we move these operations off the main thread using the async and await keywords in C#. By using FileStream with the useAsync flag set to true, we allow the operating system to handle the read/write request in the background, returning control to Unity so the rendering loop can continue uninterrupted.

Implementing Non-Blocking Saves

Here is how you can implement an asynchronous save sequence:

using System.IO;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

public class AsyncSaveManager
{
    public async Task SaveDataAsync(string path, string jsonData)
    {
        byte[] encodedText = Encoding.UTF8.GetBytes(jsonData);

        // Using FileOptions.Asynchronous allows for non-blocking I/O
        using (FileStream sourceStream = new FileStream(
            path,
            FileMode.Create, FileAccess.Write, FileShare.None,
            bufferSize: 4096, useAsync: true))
        {
            await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
        }
        
        Debug.Log("Save operation completed in the background.");
    }
}

When you call await SaveDataAsync(...) from a method, the code execution pauses at that line until the file is written, but—crucially—it does not block the Unity engine’s main thread. This means your players won't experience stuttering when you auto-save, even if the save file contains complex nested data structures or large binary blobs.

Remember that since these tasks run asynchronously, you should avoid modifying the data being saved until the Task has returned, otherwise, you may encounter race conditions where the file content becomes corrupted.

Key Takeaway: By utilizing FileStream with useAsync: true and the await keyword, you offload heavy disk operations to background threads, ensuring your frame rate remains buttery smooth during data persistence.