Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Ensuring Events Don't Stack

Tags:

c#

events

HI,

I have a button click event where a user defined type is initialised, and an event is set-up.

This button is used numerous times, and I don't want the events to stack. Therefore I have unsubscribed to the event in the finally block.

The code is similar to below:

try {
bar = new foo();
bar.event += new event(method);

dosomething()
}
finally {
bar.event -= new event(method);
}

It seems to work okay so far, however I'm concerned with the finally block being processed before the doSomething method has completed and thus made use of the event.

Would the method be allowed to process before the finally block is called?

like image 858
Darren Young Avatar asked Jul 28 '26 22:07

Darren Young


1 Answers

What I usually do is have an inEvent boolean variable that is checked every time an event is triggered. The code will look like this:

bool inEvent = false;

...

private void Button1_Click(object source, EventArgs e) 
{
    if (inEvent)
        return;

    try 
    {
        inEvent= true;

        dosomething();
    }
    finally 
    {
        inEvent = false;
    }
}
like image 59
David Božjak Avatar answered Jul 30 '26 10:07

David Božjak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!