0

I've been trying to make this work, but seems the program freeze. When i use .Result to return the binary data. I've not used Async before, sorry for my newbie code. It works perfect when i read the file as usual, but not async.

private static SaveData LoadFile()
{
    string path = "/save.dat";
    if (!File.Exists(path))
    {
        return null;
    }

    SaveData data = data = ZeroFormatterSerializer.Deserialize<SaveData>(ReadAllFileAsync(path).Result);
    return data;
}

private static async Task<byte[]> ReadAllFileAsync(string path)
{
    using (var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true))
    {
        byte[] result = new byte[file.Length];
        await file.ReadAsync(result, 0, (int)file.Length);
        return result;
    }
}
Printer
  • 457
  • 3
  • 11
  • If you are not running in a context where it is beneficial to use async/await then do not use it anywhere. Call the non-async equivalent methods instead. – Igor Apr 14 '20 at 20:03
  • Change your method signature to `private static async Task LoadFile()` and then await the call to `ReadAllFileAsync` like this: `var fileBytes = await ReadAllFileAsync(path);`. Then, you can use `ZeroFormatterSerializer.Deserialize(fileBytes);`. – 41686d6564 stands w. Palestine Apr 14 '20 at 20:03
  • How can i use the data inside LoadFile now? – Printer Apr 14 '20 at 20:42

0 Answers0