Last active
August 18, 2019 17:25
-
-
Save luisdeol/527e80739e57dcdc3ae02cd63c27d3c7 to your computer and use it in GitHub Desktop.
Using finalizers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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