Skip to content

Instantly share code, notes, and snippets.

@luisdeol
Last active August 18, 2019 17:25
Show Gist options
  • Save luisdeol/527e80739e57dcdc3ae02cd63c27d3c7 to your computer and use it in GitHub Desktop.
Save luisdeol/527e80739e57dcdc3ae02cd63c27d3c7 to your computer and use it in GitHub Desktop.
Using finalizers
using System;
namespace _26_ManageObjLifecycle
{
class Program
{
static void Main(string[] args)
{
var baseClassWithFinalizer = new BaseClassWithFinalizer();
baseClassWithFinalizer = null;
// By setting it to null, you will allow the Finalizer for that object to be executed when WaitForPendingFinalizers is called.
GC.Collect();
GC.WaitForPendingFinalizers();
Console.ReadKey();
}
}
public class BaseClassWithFinalizer
{
private UnmanagedResource _unmanagedResource;
public BaseClassWithFinalizer()
{
_unmanagedResource = new UnmanagedResource();
_unmanagedResource.DoStuff();
}
~BaseClassWithFinalizer()
{
Console.WriteLine("BaseClassWithFinalizer is being called.");
_unmanagedResource.Free();
}
}
public class UnmanagedResource
{
public void DoStuff()
{
Console.WriteLine("Doing unmanaged stuff. File access created.");
}
public void Free()
{
Console.WriteLine("Freeing Unmanaged Resource.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment