جامع القمامة (Garbage Collector - GC)

📘 درس Visual Basic - جامع القمامة (Garbage Collector - GC)


🔹 ما هو Garbage Collector؟

جامع القمامة (Garbage Collector) هو مكون في بيئة .NET Framework مسؤول عن إدارة الذاكرة بشكل تلقائي. وظيفته الرئيسية هي تحرير الذاكرة من الكائنات التي لم يعد البرنامج يحتاج إليها.


💡 لماذا نستخدم Garbage Collector؟

لأنه يوفر إدارة ذكية للذاكرة بدون الحاجة لكتابة كود يدوي لتحرير الموارد، مما يقلل الأخطاء ويحسن أداء البرنامج.


✅ كيف يعمل GC؟

  • يتتبع جميع الكائنات الموجودة في الذاكرة.
  • يحدد الكائنات التي لا يوجد مراجع إليها.
  • يقوم بتحرير الذاكرة تلقائيًا عند الحاجة.

💻 مثال مبسط يوضح مفهوم GC

في هذا المثال، يتم إنشاء كائن ثم يختفي مرجعه عند نهاية الدالة، مما يسمح للـ GC بتحريره تلقائيًا.


Public Class Person
    Public Sub SayHello()
        Console.WriteLine("مرحبًا!")
    End Sub
End Class

Module Program
    Sub CreatePerson()
        Dim p As New Person()
        p.SayHello()
        ' بعد انتهاء الدالة، يمكن للـ GC تحرير الكائن
    End Sub

    Sub Main()
        CreatePerson()
        GC.Collect() ' طلب جمع القمامة يدويًا (اختياري)
    End Sub
End Module

🌍 English Explanation

The Garbage Collector (GC) is a component in the .NET Framework responsible for automatically managing memory. Its main role is to free up memory occupied by objects that are no longer needed by the program.

💡 Why Use the Garbage Collector?

Because it provides smart memory management without requiring manual code to release resources, which reduces errors and improves application performance.

✅ How Does GC Work?

  • Tracks all objects in memory.
  • Identifies objects that are no longer referenced.
  • Automatically frees memory when needed.

💻 Simple Example Illustrating GC Concept

In this example, an object is created and then loses its reference when the method ends, allowing GC to collect it automatically.


Public Class Person
    Public Sub SayHello()
        Console.WriteLine("Hello!")
    End Sub
End Class

Module Program
    Sub CreatePerson()
        Dim p As New Person()
        p.SayHello()
        ' After this method, GC can free the object
    End Sub

    Sub Main()
        CreatePerson()
        GC.Collect() ' Manually trigger garbage collection (optional)
    End Sub
End Module

تعليقات

المشاركات الشائعة من هذه المدونة

1.1 SQL Introduction

Entity Framework - ما هو ORM؟ ونبذة عن Dapper وNHibernate

LINQ Concat Method