Latch me if you can!

In my first blog post I’ve shown a common UI problem when it comes to event handling and programmatic vs. user-triggered events on the one handside and to infinite loops due to recursive event chains on the other. With event detach/attach and boolean flags I’ve shown two simple solutions which are very common in many development projects. But they have their shortcomings and just don’t feel natural. This blog post shows an alternative which I found simple and beautiful.

Latch to the rescue

Jeremy Miller introduced the Latch design pattern as possible solution for the problem at hand. It’s a tiny beautiful, yet little know solution and the latter is a pitty. A Latch encapsulates the logic of executing an action depending on the current state of the Latch. If the Latch is in „Latched“ state, no action is executed. And actions can be executed inside of the Latch (changing the state to „Latched“), preventing other actions from executing.

Latch #1: Disposing Latch

Before reading Jeremy’s post, I’ve made a sort of Latch pattern for myself. Here the Latch implements IDisposable, and the Latched state is set on creation of the Latch and reset at a call of Dispose(). This allows the application of the using() { } syntax and the Latch state is reset automatically when exceptions occur. The Latch class would look like this:

public class Latch : IDisposable
{
    public bool IsLatched { get; private set; }

    public Latch()
    {
        IsLatched = true;
    }

    public void RunIfNotLatched(Action action)
    {
        if (IsLatched)
            return;

        action();
    }

    public void Dispose()
    {
        IsLatched = false;
    }

    public static Latch Latched
    {
        get { return new Latch(); }
    }
    public static Latch UnLatched
    {
        get { return new Latch { IsLatched = false }; }
    }
}

The RunIfNotLatched() method is just a little helper which executes an action given on the current state of the Latch. The actual application of the Latch in the example code from the previous post is shown here:

public partial class SomeControl : UserControl
{
    // ...

    private Latch _textSetByCodeLatch = Latch.UnLatched;

    private ViewData _viewData;
    public ViewData ViewData
    {
        get { return _viewData; }
        set
        {
            _viewData = value;
            if (value != null)
            {
                using (_textSetByCodeLatch = new Latch())
                {
                    _someTextBox.Text = value.SomeValue;
                }
                // other operations
            }
        }
    }

    private void OnSomeTextBoxTextChanged(object sender, EventArgs e)
    {
        _textSetByCodeLatch.RunIfNotLatched(() =>
        {
            // perform data/view update operations
        });
    }
}

At first sight I liked the using() { } syntax. It frees the application code from manually reseting the Latch to UnLatched state. At second sight I think there could be a cleaner solution. In my Latch implementation the using() { } syntax is kind of misused and could lead to irritations because there is implicit knowledge about the internal functionality of the Latch. Again, the intent is not explicitly revealed.

Latch #2: Boolean Latch

A cleaner solution with explicit methods for running actions inside of the Latch and missing action execution when other actions have entered the Latch could be the following Latch implementation:

public class Latch
{
    public bool IsLatched { get; private set; }

    public void RunLatched(Action action)
    {
        try
        {
            IsLatched = true;
            action();
        }
        finally
        {
            IsLatched = false;
        }
    }

    public void RunIfNotLatched(Action action)
    {
        if (IsLatched)
            return;

        action();
    }
}

Here the basic boolean logic behind matches with the Disposing Latch, but the syntax has changed. The Latch now contains two methods. RunLatched() executes an action inside the Latch and prevents actions from being executed in RunIfNotLatched(). Here’s the usage for this Latch type in our example:

public partial class SomeControl : UserControl
{
    // ...

    private readonly Latch _textSetByCodeLatch = new Latch();

    private ViewData _viewData;
    public ViewData ViewData
    {
        get { return _viewData; }
        set
        {
            _viewData = value;
            if (value != null)
            {
                _textSetByCodeLatch.RunLatched(() =>
                {
                    _someTextBox.Text = value.SomeValue;
                });
                // other operations
            }
        }
    }

    private void OnSomeTextBoxTextChanged(object sender, EventArgs e)
    {
        _textSetByCodeLatch.RunIfNotLatched(() =>
        {
            // perform data/view update operations
        });
    }
}

Now the Latch has a cleaner and more explicit syntax. And like the Disposing Latch it has a clean exception handling mechanism. That’s the good news. With that our Boolean Latch is applicable in most simple scenarios. But not in all! Imagine parallel execution of UI actions. Moreover imagine having two actions which should be run in RunLatched() of the same Latch object – again in parallel:

  1. Action 1 enters RunLatched() and the Latch changes its state.
  2. Action 2 enters RunLatched(), the Latch state remains in IsLatched.
  3. Action 1 leaves RunLatched() and the Latch changes its state to not latched.

Step 3 is the problem. Action 2 is still running inside the Latch, but due to the boolean logic the Latch is not latched any longer. Thus other actions are executed when given to RunIfNotLatched(), which is no help on the initial problem. This is not only true for the Boolean Latch, but for the Disposing Latch as well.

Latch #3: Counting Latch

This problem is solved by the Counting Latch, which is most similar to Jeremy’s Latch implementation. Instead of having just a boolean discriminator, it employs a counter for parallel RunLatched() calls. The IsLatched state is determined based on this counter. If it’s equal to 0, the Latch is not latched (because no method is currently running inside of RunLatched()). Else the Latch is treat as latched. Here’s the implementation of this Latch variant (edit: thanks nwiersma for the thread-safe hint):

public class Latch
{
    private readonly object _counterLock = new object();

    public int LatchCounter { get; private set; }

    public bool IsLatched
    {
        get { return (LatchCounter > 0); }
    }

    public void RunLatched(Action action)
    {
        try
        {
            lock(_counterLock) { LatchCounter++; }
            action();
        }
        finally
        {
            lock(_counterLock) { LatchCounter--; }
        }
    }

    public void RunIfNotLatched(Action action)
    {
        if (IsLatched)
            return;

        action();
    }
}

The usage in this case is equivalent to the Boolean Latch. You should note that each of these Latch implementations works, it’s just a matter of your requirements which of them you want to use. The Counting Latch as most generic Latch implementation above and applies to most situations.

Benefits of using the Latch

Using the Latch for the foresaid problems has clear advantages over the use of event detach/attach and boolean flags. First the Latch encapsulates the logic of running actions depending on a state, in this case the current execution of another action. Thus the purpose of a Latch is explicit, in contrast to the implicit intent of e.g. boolean flags. This increases code readability.

The second advantage comes with resetting the initial state. The Latch performs this task itself when an action leaves the RunLatched() method for example. With boolean flags and event detach/attach this is your task. It’s most likely getting problematic if exceptions are thrown inside an action. The Latch takes over the responsibility of automatically rolling back the state of the Latch on occurrence of an exception.

In conclusion the Latch is a pretty simple design pattern which increases readability and feels right for the problem of dependent action execution. For myself, at least I’ve found some nice solution for UI event reaction depending on the source of the trigger of the event and for infinite event loops, without relying on ugly boolean flags or event attach/detach.

kick it on DotNetKicks.com