Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code improvement: Better alternatives to this pattern?

In a similar question:
What is this pattern called? Soft Lock?

I was asking about the name of the pattern for the code listing below.

  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;
    }
  }

It seems that most of the conversation was centered around why we should an should not do this, so I think that this question provides a better forum to tackle the problem and address all of the issues. What is the better / proper way to handle this?

like image 304
A.R. Avatar asked Nov 26 '25 10:11

A.R.


1 Answers

There are series of problems with that pattern. If you want to invoke the handler only once, you would do something like this:

 protected static object _lockObj = new object();
 protected static bool _isHandled = false;    

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

     lock(_lockObj)
     {
         if(_isHandled)
            return;

         _isHandled = true;

         MyOtherPossiblyRecursiveMethod(); // Actually does all your work

         _isHandled = false;
     }
 }

 void MyOtherPossiblyRecursiveMethod()
 {
 }

This way, only one thread should be able to access the actual work method.

like image 99
Tejs Avatar answered Nov 29 '25 00:11

Tejs