I would like to read an image file asynchronously and Im trying to achieve that using async/await
from C#. However, I still notice a significant lag with this implementation. Using the profiler I'm pretty confident it is it the FileStream.ReadAsync()
method that takes ages to complete, rather than doing it asynchronously and stops the game from updating.
I notice more lag this way than just using File.ReadAllBytes
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.
Here's some code.
// Static class for reading the image.
class AsyncImageReader
{
public static async Task<byte[]> 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<byte[]> readImageTask = AsyncImageReader.ReadImageAsync(filePath);
byte [] imageBytes = await readImageTask;
// other things that use the bytes....
}