In C ++, it's pretty easy to write a Guard class that takes a reference to a variable (usually a bool), and when the instance object goes out of scope and collapses, the destructor resets the variable to its original value.
void someFunction() {
if(!reentryGuard) {
BoolGuard(&reentryGuardA, true);
// do some stuff that might cause reentry of this function
// this section is both early-exit and exception proof, with regards to restoring
// the guard variable to its original state
}
}
I am looking for an elegant way to do this in C # using a deletion template (or maybe some other mechanism?) I think passing a delegate to a call might work, but it seems a bit more error prone than the guard above. Suggestions are welcome!
Sort of:
void someFunction() {
if(!reentryGuard) {
using(var guard = new BoolGuard(ref reentryGuard, true)) {
}
}
}
With the understanding that the above code will not work.
source
share