static void Main(string[] args) { var smsSender = new SmsSender( ); var emailSender = new EmailSender( ); JokeGenerator jokeGenerator = new JokeGenerator(); jokeGenerator.JokeGenerated += (emailSender.MailJoke); jokeGenerator.JokeGenerated += (smsSender.SmsJoke); Console.WriteLine("Hit enter to remove SMS sender"); Console.ReadLine(); jokeGenerator.JokeGenerated -= (smsSender.SmsJoke); jokeGenerator = null; Console.ReadLine(); }
static void Main(string[] args) { var smsSender = new SmsSender(); var emailSender = new EmailSender(); JokeGenerator jokeGenerator = new JokeGenerator(); jokeGenerator.Subscribe(emailSender.MailJoke); jokeGenerator.Subscribe(smsSender.SmsJoke); jokeGenerator.UnSubscribe(smsSender.SmsJoke); emailSender = null; smsSender = null; jokeGenerator = null; //Please pay attention to this memory leak case: we have explicitly set jokeGenerator to null, but events still occur, so Timer object lives in memory, and the object, that contain handling method live as well GC.Collect(); Console.ReadLine(); }