-
-
Save CitizenInsane/06d898e3e3c0a380d6a7 to your computer and use it in GitHub Desktop.
This file contains 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
namespace FinalizerOrder | |
{ | |
using System; | |
using System.Diagnostics; | |
using SmartWeakEvent; | |
class Engine : IDisposable | |
{ | |
private Engine() | |
{ | |
Debug.WriteLine("ActivateEngine() ..."); | |
} | |
~Engine() | |
{ | |
dispose(false); | |
} | |
public static event EventHandler Disposing | |
{ | |
add { Singleton.disposingWeak.Add(value); } | |
remove { Singleton.disposingWeak.Remove(value); } | |
} | |
private void fireDisposing() | |
{ | |
disposingWeak.Raise(this, EventArgs.Empty); | |
} | |
private FastSmartWeakEvent<EventHandler> disposingWeak = new FastSmartWeakEvent<EventHandler>(); | |
public void Dispose() | |
{ | |
dispose(true); | |
GC.SuppressFinalize(this); | |
} | |
protected virtual void dispose(bool disposing) | |
{ | |
if (disposed) { return; } | |
fireDisposing(); | |
Debug.WriteLine("TerminateEngine() ..."); | |
disposed = true; | |
} | |
private bool disposed; | |
private static Engine Singleton | |
{ | |
get { return singleton ?? (singleton = new Engine()); } | |
} | |
private static Engine singleton; | |
} | |
class Module : IDisposable | |
{ | |
public Module() | |
{ | |
Engine.Disposing += onEngineDisposing; | |
id = counter++; | |
Debug.WriteLine("CreateModule() ==> {0} ...", id); | |
} | |
~Module() | |
{ | |
dispose(false); | |
} | |
private void onEngineDisposing(Object sender, EventArgs e) | |
{ | |
Dispose(); | |
} | |
public void Dispose() | |
{ | |
dispose(true); | |
GC.SuppressFinalize(this); | |
} | |
protected virtual void dispose(bool disposing) | |
{ | |
if (disposed) { return; } | |
Debug.WriteLine("DestroyModule({0}) ...", id); | |
Engine.Disposing -= onEngineDisposing; | |
disposed = true; | |
} | |
private bool disposed; | |
private int id; | |
private static int counter; | |
} | |
class Program | |
{ | |
static void Main() | |
{ | |
var module1 = new Module(); | |
var module2 = new Module(); | |
var weakRef = new WeakReference(module1); | |
module1 = null; | |
GC.Collect(GC.MaxGeneration); | |
GC.WaitForPendingFinalizers(); | |
Debug.Assert(weakRef.IsAlive == false); | |
GC.KeepAlive(module2); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment