Thursday, February 5, 2009

event like property plus safely CallEventHandlers

I'm showing how to define events similarly to how as you define properties... a best practice.
I'm showing how to call these event handlers in a safe way to handle exceptions... another best practice.

I've defined two events, one for save and and one for complete using the "event" keyword instead of the "property". The type is of EventHandler which has "add" and "remove" operators += and -=.

Each event has an "add" and "remove" like a property has "get" and "set".
Each event is different in another way to, using += and -= to add/remove a callback to the respective EventHandler.

Here are the events:
private event EventHandler m_Complete;
///
/// Event occurs on complete.
///

public event EventHandler Complete
{
add
{
m_Complete += value;
}
remove
{
m_Complete -= value;
}
}

private event EventHandler m_Save;
///
/// Event occurs on save.
///

public event EventHandler Save
{
add
{
m_Save += value;
}
remove
{
m_Save -= value;
}
}

The code to call the event handler has to first check to assure there IS an event handler (not null). In the for loop iterating over the individual handlers registered in the respective event "add"... the code has to catch exceptions that any of the individual handlers throws so the remaining handlers will get called.

Here is the "safe" code:

///
/// Calls the event handlers.
///

/// The save or complete event handler.
private void CallEventHandlers(EventHandler saveOrComplete)
{
// assure event exists
if (saveOrComplete != null)
{
// loop event handlers and call em'
foreach (EventHandler eh in saveOrComplete.GetInvocationList())
{
try
{
// try to call the event handler
eh(this, EventArgs.Empty);
}
catch (Exception ex)
{
string s = ex.Message;
}
}
}
}

No comments:

Post a Comment