Note that there are some explanatory texts on larger screens.

plurals
  1. POCreate, test, and raise a copy of public event's in an event handler to safeguard against exceptions in subscribers
    primarykey
    data
    text
    <p>I see alot of code that just calls the eventhandler like so:</p> <pre><code>if( OnyMyEvent != null) OnMyEvent(this,"args"); </code></pre> <p>But in this article <a href="http://www.codeproject.com/KB/cs/event_fundamentals.aspx#7.EventRaisingCode19" rel="nofollow noreferrer">C# Event Implementation Fundamentals, Best Practices and Conventions By Jeffrey Schaefer: 7) Event Raising Code</a> on <a href="http://www.codeproject.com/" rel="nofollow noreferrer">CodeProject</a> 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.</p> <p>Here is a sample (not tested/compiled) so readers get the idea:</p> <pre><code>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 ) ); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload