我一直在开发 WP7 应用程序,它是图片库应用程序,实现了基本的缩放和轻弹手势。
出于测试目的,我使用设置为 Content 的离线图像(它们的文件名已编号)编译了该应用程序,并通过硬编码字符串(稍后将被替换)访问它们。
但后来意识到该应用程序消耗大量内存。我以为是图片的原因,发现了这个博客;图像总是被缓存。我使用博客中的代码来纠正这个问题。尽管消耗率确实下降了,但仍然没有释放内存。
对于最后的尝试,我创建了另一个带有基本功能 2 按钮的测试应用程序,用于导航和图像的图像控制,只是为了确保不是我的手势代码可能是问题。
这是xml
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Image Grid.Row="0" x:Name="ImageHolder" Height="Auto" Width="Auto" Stretch="Uniform" Tap="image_Tap" />
<TextBlock x:Name="MemUsage" />
<StackPanel Grid.Row="1" Orientation="Horizontal">
<Button x:Name="PrevButton" Content="Prev" Width="240" Click="btnPrev_Click"/>
<Button x:Name="NextButton" Content="Next" Width="240" Click="btnNext_Click"/>
</StackPanel>
</Grid>
这是 .cs 文件
const int PAGE_COUNT = 42;
int pageNum = 0;
public MainPage()
{
InitializeComponent();
RefreshImage();
}
private void btnPrev_Click(object sender, RoutedEventArgs e)
{
pageNum = (PAGE_COUNT + pageNum - 1) % PAGE_COUNT; // cycle to prev image
RefreshImage();
}
private void btnNext_Click(object sender, RoutedEventArgs e)
{
pageNum = (PAGE_COUNT + pageNum + 1) % PAGE_COUNT; // cycle to next image
RefreshImage();
}
private void image_Tap(object sender, GestureEventArgs e)
{
RefreshTextData();
}
private void RefreshImage()
{
BitmapImage image = ImageHolder.Source as BitmapImage;
ImageHolder.Source = null;
if (image != null)
{
image.UriSource = null;
image = null;
}
ImageHolder.Source = new BitmapImage(new Uri("000\\image" + (pageNum + 1).ToString("D3") + ".jpg", UriKind.Relative));
RefreshTextData();
}
private void RefreshTextData()
{
MemUsage.Text = "Device Total Memory = " + (long)DeviceExtendedProperties.GetValue("DeviceTotalMemory") / (1024 * 1024)
+ "\nCurrent Memory Usage = " + (long)DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage") / (1024 * 1024)
+ "\nPeak Memory Usage = " + (long)DeviceExtendedProperties.GetValue("ApplicationPeakMemoryUsage") / (1024 * 1024);
}
但是仍然存在内存泄漏,我无法指出它。我很难找到它。内存分析器显示我有很多字符串实例,但我无法解释。
几点:
- 我在文件夹“000”中有图像并命名为“image###”。目前我有文件名从“image001”到“image042”的图像
- 测试应用程序的第一页完全显示图像后,内存占用为 6 MB,在第一页更改后,它上升到几乎 18-20 MB
- 如果图像数量允许,随后的页面更改会导致内存逐渐增加,然后最终崩溃,否则在循环浏览所有图像后内存消耗是恒定的
- 我正在使用尺寸约为 1280 x 2000 的 .jpg 文件进行测试,我没有调整图像大小。