我想知道分配給位圖的內存分配和處理如何在.NET中工作。。當沒有剩餘內存時,GC不會自動處理.Net和位圖
當我在一個函數的循環中進行了大量的位圖創建並連續調用它時,它將一直運行,直到某些時候位圖將不能分配給出指定大小的「無效參數」異常的內存。
如果我從while調用垃圾回收器的時候它工作。
用下面的代碼,你能repoduce錯誤:
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()。 – 2011-04-30 00:28:20
@Ed,儘管技術上是這樣,當GC清理位圖時,位圖的終結器將處理該資源。但是你是對的,你不應該依賴它。 – Talljoe 2011-04-30 00:33:09
@Talljoe:是的,你是對的,會的。 – 2011-04-30 00:42:36