Skip to content

Instantly share code, notes, and snippets.

@luisdeol
Created January 7, 2018 23:24
Show Gist options
  • Save luisdeol/6b0ab0856d0b86e677f26729578f2290 to your computer and use it in GitHub Desktop.
Save luisdeol/6b0ab0856d0b86e677f26729578f2290 to your computer and use it in GitHub Desktop.
Exception Handling when raising events
using System;
using System.Collections.Generic;
using System.Linq;
namespace create_implement_events_callbacks
{
class Program
{
static void Main(string[] args)
{
var pub = new Publisher();
pub.OnChange += (sender, e) => Console.WriteLine("Event nº 1 raised!");
pub.OnChange += (sender, e) => throw new Exception();
pub.OnChange += (sender, e) => Console.WriteLine("Event nº 3 raised!");
try
{
pub.Raise();
}
catch (AggregateException ex)
{
Console.WriteLine($"Number of exceptions thrown: {ex.InnerExceptions.Count}");
}
Console.ReadKey();
}
}
public class Publisher
{
public event EventHandler OnChange = delegate { };
public void Raise()
{
var exceptions = new List<Exception>();
foreach (var handler in OnChange.GetInvocationList())
{
try
{
handler.DynamicInvoke(this, EventArgs.Empty);
}
catch (Exception e)
{
exceptions.Add(e);
}
}
if (exceptions.Any())
throw new AggregateException(exceptions);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment