【发布时间】:2011-08-15 20:48:29
【问题描述】:
我想知道为位图分配的内存的分配和处置如何在 .NET 中工作。
当我在一个函数的循环中创建大量位图并连续调用它时,它将一直工作到某个时候位图将无法分配内存,给出指定大小的“无效参数”异常。
如果我从 while 到 while 调用垃圾收集器。
使用以下代码,您可以重现错误:
class BitmapObject {
public bool Visible {
get { return enb; }
set { enb = value; }
}
private bool enb;
private Bitmap bmp;
public BitmapObject(int i, bool en)
{
enb = en;
bmp = new Bitmap(i, i);
}
}
class Pool<T> where T : BitmapObject
{
List<T> preallocatedBitmaps = new List<T>();
public void Fill() {
Random r = new Random();
for (int i = 0; i < 500; i++) {
BitmapObject item = new BitmapObject(500, r.NextDouble() > 0.5);
preallocatedBitmaps.Add(item as T);
}
}
public IEnumerable<T> Objects
{
get
{
foreach (T component in this.preallocatedBitmaps)
{
if (component.Visible)
{
yield return (T)component;
}
}
}
}
}
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
for (int i = 0; i < 10; i++ )
{
Test();
// without this it breaks
//GC.Collect();
//GC.WaitForPendingFinalizers();
}
Console.ReadKey();
}
private static void Test() {
Pool<BitmapObject> pool = new Pool<BitmapObject>();
pool.Fill();
for (int i = 0; i < 100; i++)
{
var visBitmaps = pool.Objects;
// do something
}
}
}
【问题讨论】:
-
GC 从不 清理本地资源,只清理 Bitmap 对象本身。您有责任致电
Dispose()。 -
@Ed,虽然在技术上是正确的,但当 GC 清理 Bitmap 时,Bitmap 的终结器将处理资源。但你是对的,你不应该依赖它。
-
@Talljoe:是的,你是对的,它会的。
标签: c# .net memory garbage-collection bitmap