这个模式叫什么?软锁? [英] What is this pattern called? Soft Lock?

查看:125
本文介绍了这个模式叫什么?软锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有一些代码,我有时要写,主要是与UI的东西,总是与事件可以意外地卷入无限循环。

  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;
{
//代码在这里处理事件,可能再次调用MyEvent。
// IsHandlingEvent标志用于避免冗余处理。这个
//技术是什么,或者叫做模式。
// ...
}
IsHandlingEvent = false;
}
}

正如你所看到的,使用标志'IsHandlingEvent'用于防止冗余或可能无休止的事件调用。虽然我不总是这样做(因为明显的危险),有时它是一个有用的解决方案,但我不知道该叫什么。由于缺乏一个更好的术语,我一直在使用软锁。真正的名字是什么?



编辑:

是的,我知道它不是线程安全的这是一个名字问题,而不是设计问题。但是值得讨论...

代码改进:更好地替代这种模式?

解决方案

已经有很多关于设计的说法(不是线程安全的等等)。



你似乎要求一个名字...不知道这是否普遍,但我听到几次被称为可重入哨。 / p>

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?

解决方案

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.

这篇关于这个模式叫什么?软锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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