What is this pattern called? Soft Lock?

℡╲_俬逩灬. 提交于 2019-12-13 14:49:57

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7259436/what-is-this-pattern-called-soft-lock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!