问题描述
让我们创建一个:
Hi,
Let''s create a:
ObservableCollection<BitmapImage> BitmapsLists = new ObservableCollection<BitmapImage>();
然后让我们用一些随机图像填充它:
Then let''s fill it with some random Images:
foreach (string item in Directory.GetFiles("Some Folder"))
{
BitmapImage BitImage = new BitmapImage();
BitImage.BeginInit();
BitImage.CacheOption = BitmapCacheOption.None;
BitImage.UriSource = new Uri(item);
BitImage.EndInit();
BitImage.Freeze();
BitmapsLists.Add(BitImage);
}
直到这之前检查内存消耗,我们几乎不会注意到10Mb,也许更少..
(我目前正在处理50个约500 Kb的信号).
之后,让我们将位图与画布上的某些ImageSource(控件)链接起来.
Checking the memory consuption till this we will notice hardly 10Mb, maybe less..
(I am currently dealing with 50 Jpgs around 500Kb each).
After this let''s link out Bitmaps with some ImageSources of Image(controls) on a Canvas.
foreach (BitmapImage item in BitmapsLists)
{
Image myImage = new Image();
myImage.source = item;
// Then add it to Canvas Children setting Left and Top Property and calling the add function.
}
您会注意到,完成此操作后,我们将消耗大约500Mb的内存.
很好..
现在,让我们清除所有ImageSource:
You will notice that when this finishes we will have around 500Mb of memory consumption.
Fine..
Now let''s clear all of our ImageSources:
foreach (Image item in Canvas.Children)
{
item.source = null;
}
好..
现在,让我们清理孩子并使用
强制重新渲染-> InvalidateVisual(); //就像我记得的那样..
Good..
Now let''s clear our Children and force a ReRendering with
--> InvalidateVisual(); // Not Needed as i recall..
Canvas.Children.Clear;
InvalidateVisual();
好吧,现在为什么我仍然有500MB的RAM被占用..?
我没有更多的引用,并且BitmapImages仅位于集合中..
什么都没画...!
*代码块上的代码可能有一些错误,这台电脑上没有编译器..
///更新1:
阅读以下内容后,也可以尝试StreamSource: http ://stackoverflow.com/questions/1684489/how-do-you-make-sure-wpf-releases-large-bitmapsource-from-memory [ ^ ]
还是没有运气.. !!
Ok now why i still have 500MB of RAM still Being occupied..?
I have no more References and the BitmapImages are only laying into the Collection..
Nothing is being drawed...!
*Code on codeblocks may have some mistakes no compiler on this pc..
/// Update 1:
Just tryed also the StreamSource after reading this : http://stackoverflow.com/questions/1684489/how-do-you-make-sure-wpf-releases-large-bitmapsource-from-memory[^]
Still no luck..!
推荐答案
var source = new BitmapImage();
using(Stream stream = ...)
{
source.BeginInit();
source.StreamSource = stream;
source.CacheOption = BitmapCacheOption.OnLoad;
source.EndInit();
}
学分归Ray Burns所有
来自 http://stackoverflow.com/questions /1684489/how-do-you-make-sure-wpf-releases-large-bitmapsource-from-memory [ ^ ].
And the credits go to Ray Burns
from http://stackoverflow.com/questions/1684489/how-do-you-make-sure-wpf-releases-large-bitmapsource-from-memory[^].
GC.Collect();
GC.Collect方法 [ ^ ]
GC.Collect Method [^]
这篇关于BitmapImage集合内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!