大家好,我在我的 WP8 应用程序的 ScheduledAgent 中遇到了内存泄漏问题。我正在尝试做的是在循环中更新应用程序的多个图块,看起来还可以(就内存使用而言),但由于某种原因,更新图块后内存不会释放。
我的代码如下所示(Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage 测量的内存使用情况):
protected override void OnInvoke(ScheduledTask task)
{
try
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// 5MB used
foreach (int id in myIdsList)
UpdateTile(id);
});
}
catch (Exception e)
{
if (Debugger.IsAttached)
Debugger.Break();
}
NotifyComplete();
}
更新方法如下所示:
public void UpdateTile(int id)
{
MyClass myClassInstance = GetInstanceById(id);
//~6MB used by now
Canvas drawingSurface = new Canvas();
//Add some Image objects to canvas (source to each image is a filePath
// contained in myClassInstance)
//~7MB
WriteableBitmap bigTileImage = new WriteableBitmap(691, 336);
bigTileImage.Render(drawingSurface, null);
bigTileImage.Invalidate();
//~9MB
var bigTilePath = string.Format(/*path here*/);
using (IsolatedStorageFile storage =
IsolatedStorageFile.GetUserStoreForApplication())
{
if (storage.FileExists(bigTilePath))
storage.DeleteFile(bigTilePath);
using (var isoFileStream = new IsolatedStorageFileStream(
bigTilePath, FileMode.Create, storage))
{
bigTileImage.SaveJpeg(isoFileStream, bigTileImage.PixelWidth,
bigTileImage.PixelHeight, 0, 100);
}
}
ShellTile tileToUpdate = ShellTile.ActiveTiles.FirstOrDefault(
x => x.NavigationUri.ToString().Contains("TileID="+id));
FlipTileData flipTileData = new FlipTileData()
{
//Set fields
WideBackgroundImage =
new Uri(("isostore:/"+bigTilePath, UriKind.Absolute),
};
tileToUpdate.Update(flipTileData);
//~10MB used
//Shouldn't memory be released by now??
// calling GC.Collect() has no effect
}
所以,它是一个 PeriodicTask,我有 11MB 的内存上限,只要内存在迭代后没有释放,我就会得到 OutOfMemoryException。
也许我不了解基础知识,但我认为应该在将文件保存到 IS 后释放大部分占用的内存(或者每当 GC 决定收集,但是,正如我所说,即使显式调用GC.Collect()
也没有效果)?
难道我做错了什么?有没有办法释放内存?