改进代码:更好的选择这种模式? [英] Code improvement: Better alternatives to this pattern?

查看:114
本文介绍了改进代码:更好的选择这种模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个类似的问题:结果
这是什么模式叫什么名字?软锁?

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?

推荐答案

有一系列与该模式的问题。如果你想调用的处理程序只有一次,你会做这样的事情:

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.

这篇关于改进代码:更好的选择这种模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆