自从将我的代码转换为从存档中读取资源以来,我注意到我的应用程序性能略有下降。我将如何改进以下代码以帮助将性能提高到使用平面文件系统时的状态或尽可能接近时的性能。
class Resource
{
private static readonly string ResourcePath = AppDomain.CurrentDomain.BaseDirectory + "resources.pak";
private const string ResourcePassword = "0ORzjHcFxV0QXTuOizu0";
private static ZipFile Read(string filepath, string password = null)
{
var file = ZipFile.Read(filepath);
file.Password = password;
return file;
}
internal static List<string> GetFiles(string haystack, string needle = "*")
{
var resource = Read(ResourcePath, ResourcePassword).SelectEntries(needle, haystack);
return resource.Select(filepath => filepath.ToString().Replace("ZipEntry::", "")).ToList();
}
internal static MemoryStream ReadFile(string filepath)
{
var file = Read(ResourcePath, ResourcePassword);
var stream = new MemoryStream();
file[filepath].Extract(stream);
return stream;
}
internal static ImageSource StreamImage(string filepath)
{
var getFile = Resource.ReadFile(filepath);
var imageSource = new BitmapImage();
imageSource.BeginInit();
imageSource.StreamSource = getFile;
imageSource.EndInit();
return imageSource;
}
internal static int[] ImageSize(string filepath)
{
int[] sizeValues = {0, 0};
var readImage = Resource.ReadFile(filepath);
var image = new BitmapImage();
image.BeginInit();
image.StreamSource = readImage;
image.EndInit();
sizeValues[0] = image.PixelWidth;
sizeValues[1] = image.PixelHeight;
return sizeValues;
}
}
请注意,我已经删除了错误检查,以保持代码简短明了。
性能下降是什么意思? 我想你的意思是响应能力? 这可能是因为您要在主线程上解压缩这些资源。 将此工作移动到后台线程。
下面是一个使用 async/await 的 .Net 4.5 示例。 (未经测试)
class Resource
{
private static readonly string ResourcePath = AppDomain.CurrentDomain.BaseDirectory + "resources.pak";
private const string ResourcePassword = "0ORzjHcFxV0QXTuOizu0";
private static ZipFile Read(string filepath, string password = null)
{
var file = ZipFile.Read(filepath);
file.Password = password;
return file;
}
internal static List<string> GetFiles(string haystack, string needle = "*")
{
var resource = Read(ResourcePath, ResourcePassword).SelectEntries(needle, haystack);
return resource.Select(filepath => filepath.ToString().Replace("ZipEntry::", "")).ToList();
}
internal static Task<MemoryStream> ReadFile(string filepath)
{
return Task.Run(() =>
{
var file = Read(ResourcePath, ResourcePassword);
var stream = new MemoryStream();
file[filepath].Extract(stream);
return stream;
});
}
internal async static Task<ImageSource> StreamImage(string filepath)
{
var imageSource = new BitmapImage();
imageSource.BeginInit();
imageSource.StreamSource = await ReadFile(filepath);
imageSource.EndInit();
return imageSource;
}
internal async static Task<int[]> ImageSize(string filepath)
{
int[] sizeValues = { 0, 0 };
var image = new BitmapImage();
image.BeginInit();
image.StreamSource = await ReadFile(filepath);
image.EndInit();
sizeValues[0] = image.PixelWidth;
sizeValues[1] = image.PixelHeight;
return sizeValues;
}
}