How to import an event that can be canceled?

Help me complete an event that the handler can cancel.

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);
        }
    }
}
+3
source share
3 answers

You need to change this code:

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

like that:

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

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

+5
source

Have the boolean Cancel property in the BuildStartEventArgs class. Let the event handler be able to indicate this.

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

}
+1
source

BuildStartEventArgs , CancelEventArgs - .

+1

Source: https://habr.com/ru/post/1703645/


All Articles