Summary - Memory and GC
Combine IDisposable, using and GC to write a resource pool.
Summary - Memory and GC
In this group you learned the GC generations (Gen 0/1/2), resource management with IDisposable, the using statement, GC.Collect and the LOH.
Combining these, you can write code that uses managed and unmanaged resources safely. Let's now build a small resource pool and a collection check.
Exercise Add Dispose to the Pool class
Define the Pool class with : IDisposable. In public void Dispose() write Console.WriteLine("Pool closed");. In Main use using var p = new Pool();.
Show example solution
IDisposable { public void Dispose() { Console.WriteLine("Pool closed"); } }. In Main: using var p = new Pool();
Example solution:
using System;
class Pool : IDisposable
{
public void Dispose()
{
Console.WriteLine("Pool closed");
}
}
class Program
{
static void Main()
{
using var p = new Pool();
}
}
Finalizer and dispose together
Remember: using works only when the type implements IDisposable. If the class has a finalizer and was disposed, calling GC.SuppressFinalize(this) cancels the finalizer and improves performance.
A well-designed class reclaims resources via the finalizer even if Dispose was forgotten. This is a safety net; still, calling Dispose explicitly is always preferred.
Exercise LOH array and collection
In Main allocate a LOH array with byte[] buf = new byte[100000];. Print Console.WriteLine("LOH allocated");. Then call GC.Collect(); and finally Console.WriteLine("Collected");.
Show example solution
Write byte[] buf = new byte[100000]; Console.WriteLine("LOH allocated"); GC.Collect(); Console.WriteLine("Collected");
Example solution:
using System;
class Program
{
static void Main()
{
byte[] buf = new byte[100000];
Console.WriteLine("LOH allocated");
GC.Collect();
Console.WriteLine("Collected");
}
}
Test yourself
-
Which is an advantage of the using statement?
- Automatic Dispose at block end
- It speeds up the GC
- It resizes memory
- It creates threads
Show answer
Automatic Dispose at block end — Correct. using calls Dispose at block end.
-
Match the concepts
- IDisposable
- Dispose() method
- using
- Automatic Dispose
- GC.Collect()
- Force collection
- LOH
- ~85 KB+ objects