Created
January 7, 2018 23:24
-
-
Save luisdeol/6b0ab0856d0b86e677f26729578f2290 to your computer and use it in GitHub Desktop.
Exception Handling when raising events
This file contains hidden or 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
| 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