What is this pattern called? Soft Lock?
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 patt开发者_如何学Pythonern 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.
I think this is somewhat related to a Semaphore, i.e.: looking access to something with a boolean variable.
Edit: As pointed in the question's comment, this "pattern" should be avoided due to not being threadsafe, exception-safe and good.
精彩评论