Alex Rivera | Logout

Calling an event handler in C#

Asked 2012-08-31T14:40:21.353
11

I've been trying to learn how to use event handlers in C# but I can't figure out what handler(this, e) does in the following code:

public event EventHandler ThresholdReached;

protected virtual void OnThresholdReached(EventArgs e)
{
    EventHandler handler = ThresholdReached;
    if (handler != null)
    {
        handler(this, e);
    }
}

Is it trying to call the event handler method (this) with the event (e)?

Edit
Report

3 Answers

1

The code in your example copies all registered handlers to the local variable handler, checks that the invocation list is not empty and invokes all members of the copied invocation list with the arguments this and e.

The reason for the fact that you get a snapshot of the current invocation list is that delegates are immutable. You get a reference to the current multicast delegate, and when handlers are added or removed the backing field points to a new delegate created from two immutable ones.

The usual reason to copy the invocation list to a local variable is some form of thread-safety: a handler could be unsubscribed between the usual nullity check (check that the invocation list isn't empty) and the actual invocation: that way you might accidentally fire an event with no handlers and a NullReferenceException would be thrown.

answered 2012-08-31T15:31:01.763
0

Is it trying to call the event handler method (this) with the event (e)?

No, not literally. It is calling the event handler with the EventArgs e and using this as sender. It might as well be:

if (ThresholdReached != null)
{
    ThresholdReached(this, e);
}

Or, to circumvent the null check:

public event EventHandler ThresholdReached = delegate { };

protected virtual void OnThresholdReached(EventArgs e)
{
    ThresholdReached(this, e);
}

But, as @Oded noted, the first piece isn't thread-safe, because EventHandler handler = ThresholdReached creates a copy of the handler, which is better explained in this question.

answered 2012-08-31T14:41:42.733
0

It is Triggering the ThresholdReached event. Passing a reference to itself, this. Passing arguments about the event in e.

answered 2012-08-31T14:43:37.450

Your Answer