在类似的问题中:
这种模式叫什么?软锁? https://stackoverflow.com/questions/7259436/what-is-this-pattern-called-soft-lock
我询问下面的代码清单的模式名称。
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()
{
}
这样,只有一个线程应该能够访问实际的工作方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)