I'm trying to learn raising and handling events in C#.
Here's my simple example:
/////////////// creating a new BALL object ///
ballClass ball = new ballClass();
void button1_Click(object sender, EventArgs e)
{
// this should make the BALL object raise an event
ball.onHit();
label1.Text = "EVENT SEND";
}
// when event is fired, label text should change
void BallInPlayEvent(object sender, EventArgs e)
{
label2.Text = "EVENT FOUND!";
}
and the ball class:
class ballClass
{
public event EventHandler BallInPlay;
public void onHit()
{
this.BallInPlay ///// ??? how should i raise this event?
}
}
In the call I can't really understand, how do I raise the event? Any ideas?... :)
Thanks!
public void onHit()
{
if(BallInPlay != null)
BallInPlay(this, new EventArgs());
}
It's simple, just call the delegate directly, as in
BallInPlay(this, EventArgs.Empty);
The only thing you need to be careful about is a race condition, where BallInPlay is null or set to null before you call it.
The pattern to deal with that is
var bip = BallInPlay;
if (bip != null)
bip(this, EventArgs.Empty);
Usually, to avoid testing the handler every time (as Ed Guiness showed), it is (IMHO) easier to simply initialize the event with an empty delegate, and then call it without checking:
class Ball
{
// add an empty delegate to our handler
public event EventHandler BallInPlay = delegate { };
protected virtual void OnHit(EventArgs e)
{
// no need to check, we have at least one
// dummy delegate in the invocation list
BallInPlay (this, e);
}
}
Actually (although Jon Skeet will probably tell you this before I finish writing this post :), the only truly thread safe event call is the one discussed by in Jon Skeet's article .
Another important thing you should note is that classes shouldn't really fire events which reside in other classes (ie OnHit
method should not be public
). If a class has a public event (like your BallClass
), it alone should be the one to fire this event.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.