I see alot of code that just calls the eventhandler like so:
if( OnyMyEvent != null)
OnMyEvent(this,"args");
But in this article C# Event Implementation Fundamentals, Best Practices and Conventions By Jeffrey Schaefer: 7) Event Raising Code on CodeProject he describes a way to raise events so that exceptions subscribers doesnt affect the raiser. I'm curious if this is a best practice that should be applied.
Here is a sample (not tested/compiled) so readers get the idea:
public delegate void MessageReceivedEventHandler(object sender, MessageEventArgs e);
class MessageEventArgs : EventArgs
{
public string Message
{ get; set; }
public MessageEventArgs( string message )
{ this.Message = message; }
}
class EventTriggeringClass
{
public event MessageReceivedEventHandler MessageReceived;
protected virtual void OnMessageReceived( MessageEventArgs e )
{
this.RaiseTriggerOnMessageReceived( e );
}
private void RaiseOnMessageReceived( MessageEventArgs e )
{
MessageReceivedEventHandler handler = this.MessageReceived;
if ( handler != null )
{
Delegate[] eventHandlers = handler.GetInvocationList();
foreach ( Delegate currentHandler in eventHandlers )
{
MessageReceivedEventHandler currentSubscriber = ( currentHandler as MessageReceivedEventHandler );
try
{
currentSubscriber( this, e );
}
catch ( Exception ex )
{
Debug.Assert( ex == null, ex.Message, ex.ToString() );
}
}
}
}
public void Read()
{
bool foundMessage = false, hasMoreMessages = true;
string msg;
while( hasMoreMessages )
{
// this way or..
if( foundMessage )
this.OnMessageReceived( new MessageEventArgs( msg ) );
// the other way
if( MessageReceived != null )
MessageReceived(this, new MessageEventArgs( msg ) );
}
}
}