Is there a concise way to safely invoke events in C#.Net. I would like to safely deal with no subscribers and exceptions subscribers might throw…
I kinda want a TryInvoke method on Delegate..ideally where I could pass an exception handler too. I am in .Net 3.5 so don’t have extension methods…
Anyway here is the boilerplate I typically use.
void fireListChanged(List<string> paths)
{
try
{
if (ListChanged != null)
{
ListChanged(paths);
}
}
catch (System.Exception ex)
{
m_output.write(ex);
}
}
public event ListStringChangedDlgt ListChanged;
Just use the
= delegate {}pattern. The bonus compared to your solution is that it’s thread safe.I also recommend that you use
EventHandlerorEventHandler<YourEventArgClass>as delegate for the event.