我又要和OutOfMemoryException打架了。
我有在Windows Phone后台代理任务中使用WriteableBitmapEx渲染一些图像的代码片段(内存使用限制接近10M)。
下面的代码运行得很好:
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
var wbBG = BitmapFactory.New(0, 0);
var bmp = BitmapFactory.New(0, 0);
for (int i = 0; i < 30; i++)
{
using (var iso = IsolatedStorageFile.GetUserStoreForApplication())
{
wbBG = BitmapFactory.New(0, 0).FromContent("Assets/image" + i + ".jpg");
wbBG.Invalidate();
for (int j = 0; j < 6; j++)
{
bmp = BitmapFactory.New(0, 0).FromContent("Assets/" + j + ".png");
bmp = bmp.Resize(60, 60, WriteableBitmapExtensions.Interpolation.Bilinear);
wbBG.Blit(new Rect(j * 65, 0, 60, 60), bmp, new Rect(0, 0, 60, 60));
wbBG.Invalidate();
}
string filenameBG = "/Shared/" + i + ".jpg";
using (var stream = iso.CreateFile(filenameBG))
{
wbBG.SaveJpeg(stream, 480, 800, 0, 85);
stream.Close();
}
wbBG = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
NotifyComplete();
});但是,如果我在循环中添加或更改为使用TextBlock,它将在使用OutOfMemoryException的第二个循环中失败
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
var wbBG = BitmapFactory.New(0, 0);
TextBlock tb;
for (int i = 0; i < 30; i++)
{
using (var iso = IsolatedStorageFile.GetUserStoreForApplication())
{
wbBG = BitmapFactory.New(0, 0).FromContent("Assets/image" + i + ".jpg");
//The above line would thrown OutOfMemoryException in the 2nd loop
wbBG.Invalidate();
for (int j = 0; j < 6; j++)
{
tb = new TextBlock(){
Text = j.ToString(),
//FontSize = 13,
//Height = 20,
//Width = 240,
//FontWeight = System.Windows.FontWeights.Bold,
//HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
//Foreground = new SolidColorBrush(Colors.White)
};
wbBG.Render(tb, new TranslateTransform() { X = j*65, Y = 350 });
wbBG.Invalidate();
tb = null;
}
string filenameBG = "/Shared/" + i + ".jpg";
using (var stream = iso.CreateFile(filenameBG))
{
wbBG.SaveJpeg(stream, 480, 800, 0, 85);
stream.Close();
}
wbBG = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
NotifyComplete();
});你知道为什么TextBlock会导致更多的内存使用吗?
此外,我看不到有更好的方法来渲染图像上的文本。
此外,TextBlock不是IDisposable。
好吧,这是我的观点,可能是错的,我很感谢任何人的帮助,谢谢!
发布于 2014-03-08 17:00:08
我不知道这个库,但是当资源不再使用时,您忘记了释放它们,所以试试这个:
for (var i = 0; i < 30; i++)
{
using (var iso = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var wbBG = BitmapFactory.New(0, 0).FromContent("Assets/image" + i + ".jpg"))
{
wbBG.Invalidate();
for (int j = 0; j < 6; j++)
{
var tb = new TextBlock()
{
Text = j.ToString(),
//FontSize = 13,
//Height = 20,
//Width = 240,
//FontWeight = System.Windows.FontWeights.Bold,
//HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
//Foreground = new SolidColorBrush(Colors.White)
};
wbBG.Render(tb, new TranslateTransform() { X = j * 65, Y = 350 });
wbBG.Invalidate();
}
using (var stream = iso.CreateFile("/Shared/" + i + ".jpg"))
{
wbBG.SaveJpeg(stream, 480, 800, 0, 85);
}
}
}
}https://stackoverflow.com/questions/22219779
复制相似问题