views:

138

answers:

3

Help me please to implement an event, which handler can cancel it.

public class BuildStartEventArgs : EventArgs
{
    public bool Cancel { get; set; }
}

class Foo
{
    public event EventHandler<BuildStartEventArgs> BuildStart;

    private void Bar()
    {
     // build started
     OnBuildStart(new BuildStartEventArgs());
     // how to catch cancellation?
    }

    private void OnBuildStart(BuildStartEventArgs e)
    {
     if (this.BuildStart != null)
     {
      this.BuildStart(this, e);
     }
    }
}
+4  A: 

You need to modify this code:

private void Bar()
{
    // build started
    OnBuildStart(new BuildStartEventArgs());
    // how to catch cancellation?
}

to something like this:

private void Bar()
{
    var e = new BuildStartEventArgs();
    OnBuildStart(e);
    if (!e.Cancel) {
      // Do build
    }
}

Classes in .NET have reference semantics, so you can see any changes made to the object the parameter of the event references.

Richard
Thanks! I thought it would be much harder
abatishchev
Not everything in programming is difficult... it just seems that way :-)
Richard
A: 

Have a boolean Cancel property on the BuildStartEventArgs class. Let the event handler(s) be able to flag this.

private void Bar()
{
  // build started
  var args = new BuildStartEventArgs();
  OnBuildStart(args);
  if (args.Cancel)
  {
    // cancel
  }

}
baretta
There is already a boolean Cancel property on the BuildStartEventArgs class in the example in the question.
bzlm
worth downvoting?
baretta
+1  A: 

Your BuildStartEventArgs are redundant, the framework already offers the CancelEventArgs class – consider using it.

Konrad Rudolph
Thanks for tip. But my class has additional properties, I just didn't wrote them here.
abatishchev
But you can inherit from CancelEventArgs!
rstevens