static void Main(string[] args) { using (var l_dependent = new Dependent()) { SomethingHappened(null, EventArgs.Empty); } try { // This call will cause the disposed object // (which is still registered to the event) // to thrown an exception. SomethingHappened(null, EventArgs.Empty); } catch (InvalidOperationException e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(e.ToString()); } Console.ReadKey(true); }
static void Main(string[] args) { using (var l_dependent = new Dependent()) { SomethingHappened(null, EventArgs.Empty); } // Just to prove the point, garbage collection // will not clean up the dependent object, even // though it has been disposed. GC.Collect(); try { // This call will cause the disposed object // (which is still registered to the event) // to throw an exception. SomethingHappened(null, EventArgs.Empty); } catch (InvalidOperationException e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(e.ToString()); } Console.ReadKey(true); }