c# - 代码改进 : Better alternatives to this pattern?

标签 c# design-patterns

在类似的问题中:
What is this pattern called? Soft Lock?

我问的是下面代码 list 的模式名称。

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

似乎大部分对话都围绕着为什么我们应该和不应该这样做,所以我认为这个问题提供了一个更好的论坛来解决问题和解决所有问题。处理此问题的更好/正确方法是什么?

最佳答案

该模式存在一系列问题。如果你只想调用处理程序一次,你可以这样做:

 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()
 {
 }

这样一来,只有一个线程应该能够访问实际的工作方法。

关于c# - 代码改进 : Better alternatives to this pattern?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7259939/

相关文章:

c# - WPF应用程序遇到问题需要关闭,如何获得好的消息?

node.js - 将结果返回给外部函数

c# - VS2010/C# : How do you set the default value of a ComboBox in the IDE?

C#线程函数

c# - Linq 到实体。空引用异常

sql - 我如何更改 php 中的模式?

c# - 将命令模式调整为建立多个 API 连接的单例

android - 使用接口(interface)在 fragment 和 fragment Activity 之间进行通信是否好

javascript - 如何组合匿名函数?

c# - 使用匿名类型——如何避免大量代码