Friday, March 21, 2008

A Defensive .NET Event Technique

I was reading a recent post by Rob Eisenberg .NET Event Techniques and liked the idea presented. Here is what Rob presented...

public delegate void MyEventHandler(object sender, System.EventArgs e);
public event EventHandler Updated = delegate { };

protected void UpdatePrice(string tickerSymbol, decimal newPrice, long newVolume)
{
_priceList[tickerSymbol] = newPrice;
_volumeList[tickerSymbol] = newVolume;

Updated(this, new MarketFeedEventArgs(tickerSymbol, newPrice, newVolume));
}
To extend the original idea, I added the defensive block I usually use around it.
public event EventHandler Updated = delegate { };

protected void UpdatePrice(string tickerSymbol, decimal newPrice, long newVolume)
{
foreach (EventHandler handler in this.Updated.GetInvocationList())
{
 _priceList[tickerSymbol] = newPrice;
 _volumeList[tickerSymbol] = newVolume;

 try
 {
  handler(this, new MarketFeedEventArgs(tickerSymbol, newPrice, newVolume));
 }
 catch (System.Exception ex)
 {
  // log exception, continue
 }
}
}
This ensures the following: - No assumption that the delegate has a try/catch around its implementation - We capture the exception and handle it (log it, or do other things) - We can continue to notify others interested in the event