1
\$\begingroup\$

Changing TextBox.Text within the TextBox.TextChanged event can trigger a recursive call to the same event handler. My class EventHelper is designed to separate the action performed in the event handler from the mechanism that prevents the recursive calls. The calls can be used as in:

public static class EventHelperTest
{
    public static void ExampleUsage()
    {
        var eventHelper = new EventHelper();

        var textBox = new TextBox();
        textBox.TextChanged += (s, e) => eventHelper.ExecuteOnce(() =>
        {
            textBox.Text = textBox.Text + "a";
        });

        textBox.Text = "trigger ";

        Debug.Assert(textBox.Text == "trigger a");
    }
}

where the EventHelper is:

public class EventHelper
{
    bool skip;

    public void ExecuteOnce(Action f)
    {

        if (skip)
            return;

        skip = true;
        f();
        skip = false;
    }
}

I am looking for a review of the EventHelper class.

\$\endgroup\$
2
\$\begingroup\$

You can improve the EventHelper by reusing the sender argument so that you have only a single instance of the helper. The helper maintains a HashSet<object> that stores senders that are currently handled. This will allow you to use the return value of the Add method which is false if the sender already has been added an thus acts like your skip variable. Finally you Remove the sender from the set as if you were setting skip to false.

public class EventHelper
{
    private readonly ISet<object> _senders = new HashSet<object>();

    public void ExecuteOnce(object sender, Action action)
    {
        if (!_senders.Add(sender))
        {
            return;
        }

        action();
        _senders.Remove(sender);
    }
}

You would now call it with one more parameter:

eventHelper.ExecuteOnce(s, () =>

As far as the code is concerned you should always use {} and perhaps parameter names longer then a single letter f.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.