मैं सोच रहा हूं कि बिटमैप्स के लिए आवंटित स्मृति का आवंटन और निपटान .NET में कैसे काम करता है।.NET और बिटमैप स्वचालित रूप से जीसी द्वारा निपटाया नहीं जाता है जब कोई स्मृति नहीं होती है
जब मैं किसी फ़ंक्शन में लूप में बहुत सी बिटमैप रचनाएं करता हूं और इसे उत्तराधिकार में कॉल करता हूं तो यह तब तक काम करेगा जब तक बिटमैप निर्दिष्ट आकार के लिए अपवाद "अमान्य पैरामीटर" को स्मृति आवंटित करने में सक्षम नहीं होगा।
यदि मैं कचरा कलेक्टर को काम करता हूं, जबकि यह काम करता है।
निम्नलिखित कोड आप त्रुटि 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
}
}
}
जीसी * कभी भी मूल संसाधनों को साफ नहीं करता है, केवल बिटमैप ऑब्जेक्ट ही। आप 'निपटान() 'को कॉल करने के लिए ज़िम्मेदार हैं। –
@Ed, तकनीकी रूप से सत्य होने पर, जब जीसी बिटमैप को साफ करता है तो बिटमैप का अंतिमकर्ता संसाधन का निपटान करेगा। लेकिन आप सही हैं कि आपको उस पर भरोसा नहीं करना चाहिए। – Talljoe
@ टल्जोज़: हाँ, आप सही हैं, यह होगा। –