Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this pattern called? Soft Lock?

Here is a bit of code that I have to write sometimes, mostly in conjunction with UI stuff, and always with events that can accidentally wind up in infinite loops.

  public class MyClass
  {
    public event EventHandler MyEvent;
    private bool IsHandlingEvent = false;

    public MyClass()
    {
      MyEvent += new EventHandler(MyClass_MyEvent);
    }

    void MyClass_MyEvent(object sender, EventArgs e)
    {
      if (IsHandlingEvent) { return; }

      IsHandlingEvent = true;
      {
        // Code goes here that handles the event, possibly invoking 'MyEvent' again.
        // IsHandlingEvent flag is used to avoid redundant processing.  What is this
        // technique, or pattern called.
        // ...
      }
      IsHandlingEvent = false;
    }
  }

As you can see, using the flag 'IsHandlingEvent' is used to prevent redundant, or possible endless event invocations. While I don't always do stuff like this (because of obvious dangers), sometimes it is a useful solution, but I don't know what to call it. For lack of a better term, I have been using "soft lock". What is the real name?

EDIT:
Yes, I know that it isn't threadsafe, etc. This is a name question, not a design question. But since it is worth discussing...
Code improvement: Better alternatives to this pattern?

like image 881
A.R. Avatar asked Mar 09 '26 01:03

A.R.


2 Answers

There is already alot said about the design (being not thread-safe etc.).

You seem to ask for a name... don't know if this widespread but I heard it several times referered to as a reentrancy sentinel.

like image 95
Yahia Avatar answered Mar 11 '26 15:03

Yahia


I think this is somewhat related to a Semaphore, i.e.: looking access to something with a boolean variable.

Edit: As pointed in the question's comment, this "pattern" should be avoided due to not being threadsafe, exception-safe and good.

like image 22
Clement Herreman Avatar answered Mar 11 '26 13:03

Clement Herreman



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!