Reputation: 1312
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;
Upvotes: 1
Views: 343
Reputation: 101150
Just use the = delegate {}
pattern. The bonus compared to your solution is that it's thread safe.
void fireListChanged(List<string> paths)
{
try
{
ListChanged(paths);
}
catch (System.Exception ex)
{
m_output.write(ex);
}
}
public event ListStringChangedDlgt ListChanged = delegate {};
I also recommend that you use EventHandler
or EventHandler<YourEventArgClass>
as delegate for the event.
Upvotes: 3