Skip to content

Instantly share code, notes, and snippets.

@MisterKidX
Created October 14, 2022 11:34
Show Gist options
  • Save MisterKidX/4cfd9450aaad40ba36c92e905e81995c to your computer and use it in GitHub Desktop.
Save MisterKidX/4cfd9450aaad40ba36c92e905e81995c to your computer and use it in GitHub Desktop.
Demonstrates the use of IDisposable
Console.WriteLine("Creating 50 NotDisposable objects which will" +
" allocate 500mb of memory and will not clean at garbage collection.");
Console.ReadLine();
if(true)
{
NotDisposableContainer container = new NotDisposableContainer();
container.ND = new List<NotDisposable>();
for (int i = 0; i < 50; i++)
container.ND.Add(new NotDisposable());
Console.ReadLine();
}
Console.WriteLine("Creating 50 Disposable objects which will" +
" allocate 500mb of memory and will clean at garbage collection.");
Console.ReadLine();
if (true)
{
for (int i = 0; i < 50; i++)
{
using (Disposable d = new Disposable())
{
}
}
}
Console.WriteLine("Press enter to cleanup.");
Console.ReadLine();
GC.Collect();
Console.ReadLine();
class NotDisposableContainer
{
public List<NotDisposable> ND;
}
class Disposable : IDisposable
{
MemoryStream _ms;
byte[] buffer = new byte[10_000_000]; // 10mb
public Disposable()
{
for (int i = 0; i < 10_000_000; i++)
{
buffer[i] = (byte)i;
}
_ms = new MemoryStream(buffer);
}
public void Dispose()
{
_ms.Dispose();
GC.SuppressFinalize(this);
}
~Disposable()
{
Dispose();
}
}
class NotDisposable
{
MemoryStream _ms;
byte[] buffer = new byte[10_000_000]; // 10mb
public NotDisposable()
{
for (int i = 0; i < 10_000_000; i++)
{
buffer[i] = (byte)i;
}
_ms = new MemoryStream(buffer);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment