You can do something like this:
public static void CallAllAndCatch(this Action self) { if (self == null) return; foreach (Action i in self.GetInvocationList()) { try { i(); } catch { } } }
Note that you can use generics if you find that you do this a lot with, for example, EventHandler<T> , but you cannot generally do this for any delegate of any type, because delegate types cannot be assigned between by themselves, even if they are compatible, and there is no mechanism in determining a common method for restricting a specific general parameter to a delegate with a specific signature. (I think delegates with identical signatures are considered compatible types starting with .NET 4.)
For the EventHandler<T> approach:
public static void CallAllAndCatch(this EventHandler<T> self, object sender, T args) where T : EventArgs { if (self == null) return; foreach (EventHandler<T> i in self.GetInvocationList()) { try { i(sender, args); } catch { } } }
If you don't mind throwing performance and compile time while checking the handset, you can do this, which will work with any type of delegation:
public static void CallAllAndCatch(this Delegate self, params object[] args) where T : EventArgs { if (self == null) return; foreach (Delegate i in self.GetInvocationList()) { try { i.DynamicInvoke(args); } catch (MemberAccessException) { throw; }
source share