C# pattern block to set a variable to a begin value, do some work and reset variable with a end value

Viewed 82

I'm trying to optimize the following workflow:

myObj.SupressEvents = true;
DoSomeWork();
DoSomeMoreWork();
...
myObj.SupressEvents = false;

The problem with that is obvious, either myObj.SupressEvents = true/false; can be missed in between and lead unwanted errors or simply a by use a return can make that reset to false never to be reached, i'm looking for a pattern that avoid forgeting it, something like:

// This is a keyword example, not a function call nor definition
SetAndReset(myObj.SupressEvents, true, false)
{
   DoSomeWork();
   DoSomeMoreWork();
   ...
}

I guess this can be done with a delegate or a function with Func, but can it work even if i do a return in between it would reset the variable to false anyway? There are something like that into native C# keywords?

2 Answers

You can declare a method that takes an Action (the work you want to do) and wrap the calls inside that method:

void Wrap(Action action, object myObj /* Replace with actual type, or remove parameter if field in class */)
{
    myObj.SupressEvents = true;
    action.Invoke();
    myObj.SupressEvents = false;
}

You can call the method like so:

Wrap(() => 
{
    DoSomeWork();
    DoSomeMoreWork();
});

As improvement to @Hayden solution i like to post a bullet proof version which also takes care of exceptions which can happen and also broke the state of variable:

public void SuppressRebuildPropertiesWork(Action action)
{
    SuppressRebuildPropertiesWork(() =>
    {
        action.Invoke();
        return true;
    });
}

public bool SuppressRebuildPropertiesWork(Func<bool> action)
{
    bool result;
    try
    {
        SuppressRebuildProperties = true;
        result = action.Invoke();
    }
    catch (Exception e)
    {
        Debug.WriteLine(e);
        throw;
    }
    finally
    {
        SuppressRebuildProperties = false;
    }
    
    return result;
}
Related