【发布时间】:2019-02-20 19:15:57
【问题描述】:
我想异步读取图像文件,我尝试使用 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....
}
【问题讨论】:
-
您的代码甚至无法编译,因为您的 AddImage 方法应该是异步的
-
你的文件有多大?
-
请注意,
async方法始终在调用线程上运行,直到到达实际的await语句(实际上意味着它是 IO 绑定的)。另请注意,当此await完成时,工作将返回到同一(调用)线程。从理论上讲,这可能是滞后的原因。 -
@touseefbsb 我知道 IDE 告诉我的。这是代码的副本。
-
@PoulBak 文件不是很大,但 CPU 很垃圾。尝试与 Hololens 合作
标签: c# .net unity3d uwp hololens