我想要异步地读取一个图像文件,尝试使用C#中的async/await
实现。但是我仍然注意到这种实现存在显着的延迟。使用分析器,我非常有信心认为是FileStream.ReadAsync()
方法需要很长时间才能完成,而不是以异步方式完成并停止游戏更新。
我发现这种方式比简单地使用File.ReadAllBytes
方法更耗时,这很奇怪。我不能使用那个方法,因为它仍会导致一些延迟,我希望没有帧速率的停顿。
下面是一些代码:
// 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....
}
async
方法总是在调用线程上运行,直到实际达到await
语句(实际意义是它受到 IO 限制)。同时请注意,当此await
完成后,工作将返回到相同的(调用)线程。这可能理论上是延迟的原因。 - Martin Zikmund