改进代码:更好的选择这种模式? [英] 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?
推荐答案
有一系列与该模式的问题。如果你想调用的处理程序只有一次,你会做这样的事情:
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屋!