Tuesday, July 1, 2008

Thread Safe .NET Event Technique

Event Implementation should be done like this :

public event EventHandler Updated = delegate { };

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

Updated(this, new MarketFeedEventArgs(mySymbol, newPrice, newVolume));
}


Because in case of multithreaded environment if the event updated is not subscribed or if null it. Removes the subscription from all the other event handler. So instead of making a new copy of event each time, we should initialize the events at the first case.

People normally use like this which is performance friendly but not good practice for multithreaded environ
public event EventHandler Updated;

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

if(Updated != null)
Updated(this, new MarketFeedEventArgs(mySymbol, newPrice, newVolume));
}

No comments: