Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@CitizenInsane
Last active January 2, 2016 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CitizenInsane/06d898e3e3c0a380d6a7 to your computer and use it in GitHub Desktop.
Save CitizenInsane/06d898e3e3c0a380d6a7 to your computer and use it in GitHub Desktop.
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