Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement an event which can be canceled?

Tags:

c#

.net

events

Help me 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);
        }
    }
}
like image 268
abatishchev Avatar asked Nov 01 '25 22:11

abatishchev


2 Answers

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.

like image 150
Richard Avatar answered Nov 03 '25 12:11

Richard


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

like image 41
Konrad Rudolph Avatar answered Nov 03 '25 13:11

Konrad Rudolph