title: Read an image file asynchronously
body: <p>I would like to read an image file asynchronously and Im trying to achieve that using <code>async/await</code> from C#. However, I still notice a significant lag with this implementation. Using the profiler I'm pretty confident it is it the <code>FileStream.ReadAsync()</code> method that takes ages to complete, rather than doing it asynchronously and stops the game from updating. </p>
  
  <p>I notice more lag this way than just using <code>File.ReadAllBytes</code> which is odd. I can't use that method that still causes some lag and I would like to not have a stop in frame rate. </p>
  
  <p>Here's some code.</p>
  
  <pre><code>// Static class for reading the image.
  class AsyncImageReader
  {
      public static async Task&lt;byte[]&gt; ReadImageAsync(string filePath)
          {
              byte[] imageBytes;
              didFinishReading = false;
              using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true))
              {
                  imageBytes = new byte[fileStream.Length];
                  await fileStream.ReadAsync(imageBytes, 0, (int) fileStream.Length);
  
              }
  
              didFinishReading = true;
  
              return imageBytes;
          }
   }
  
      // Calling function that is called by the OnCapturedPhotoToDisk event. When this is called the game stops updating completely rather than 
      public void AddImage(string filePath)
      {
          Task&lt;byte[]&gt; readImageTask = AsyncImageReader.ReadImageAsync(filePath);
          byte [] imageBytes = await readImageTask;
          // other things that use the bytes....
      }
  </code></pre>