{"id":968,"date":"2010-08-04T08:22:38","date_gmt":"2010-08-04T07:22:38","guid":{"rendered":"http:\/\/www.minddriven.de\/?p=968"},"modified":"2010-08-06T16:12:19","modified_gmt":"2010-08-06T15:12:19","slug":"latch-design-pattern","status":"publish","type":"post","link":"https:\/\/www.minddriven.de\/index.php\/technology\/development\/design-patterns\/latch-design-pattern","title":{"rendered":"Latch me if you can!"},"content":{"rendered":"<p>In my <a href=\"http:\/\/www.minddriven.de\/index.php\/technology\/development\/design-patterns\/common-ui-problem\">first blog post<\/a> I&#8217;ve shown  a <strong>common UI problem<\/strong> 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&#8217;ve shown two simple solutions which are very common  in many development projects. But they have their shortcomings and just don&#8217;t feel <em>natural<\/em>. This blog post shows an alternative which I found  simple and beautiful.<\/p>\n<h3>Latch to the rescue<\/h3>\n<p>Jeremy Miller introduced the <a href=\"http:\/\/codebetter.com\/blogs\/jeremy.miller\/archive\/2007\/07\/02\/build-your-own-cab-12-rein-in-runaway-events-with-the-quot-latch-quot.aspx\">Latch design pattern<\/a> as possible solution for the  problem at hand. It&#8217;s a tiny beautiful, yet little know solution and  the latter is a pitty. A <strong>Latch<\/strong> encapsulates the logic of executing an  action depending on the current state of the Latch. If the Latch is in  &#8222;Latched&#8220; state, no action is executed. And actions can be executed inside  of the Latch (changing the state to &#8222;Latched&#8220;), preventing other actions  from executing.<\/p>\n<h3>Latch #1: Disposing Latch<\/h3>\n<p>Before reading Jeremy&#8217;s post, I&#8217;ve made a sort of Latch pattern for myself. Here the Latch implements <code>IDisposable<\/code>, and the Latched state is set on creation of the Latch and  reset at a call of <code>Dispose()<\/code>. This allows the application of the <code>using() { }<\/code> syntax and the Latch state is reset automatically when exceptions  occur. The <code>Latch<\/code> class would look like this:<\/p>\n<pre class=\"brush:csharp\">public class Latch : IDisposable\r\n{\r\n    public bool IsLatched { get; private set; }\r\n\r\n    public Latch()\r\n    {\r\n        IsLatched = true;\r\n    }\r\n\r\n    public void RunIfNotLatched(Action action)\r\n    {\r\n        if (IsLatched)\r\n            return;\r\n\r\n        action();\r\n    }\r\n\r\n    public void Dispose()\r\n    {\r\n        IsLatched = false;\r\n    }\r\n\r\n    public static Latch Latched\r\n    {\r\n        get { return new Latch(); }\r\n    }\r\n    public static Latch UnLatched\r\n    {\r\n        get { return new Latch { IsLatched = false }; }\r\n    }\r\n}<\/pre>\n<p>The  <code>RunIfNotLatched()<\/code> 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 <a href=\"http:\/\/www.minddriven.de\/index.php\/technology\/development\/design-patterns\/common-ui-problem\">previous post<\/a> is shown here:<\/p>\n<pre class=\"brush:csharp\">public partial class SomeControl : UserControl\r\n{\r\n    \/\/ ...\r\n\r\n    private Latch _textSetByCodeLatch = Latch.UnLatched;\r\n\r\n    private ViewData _viewData;\r\n    public ViewData ViewData\r\n    {\r\n        get { return _viewData; }\r\n        set\r\n        {\r\n            _viewData = value;\r\n            if (value != null)\r\n            {\r\n                using (_textSetByCodeLatch = new Latch())\r\n                {\r\n                    _someTextBox.Text = value.SomeValue;\r\n                }\r\n                \/\/ other operations\r\n            }\r\n        }\r\n    }\r\n\r\n    private void OnSomeTextBoxTextChanged(object sender, EventArgs e)\r\n    {\r\n        _textSetByCodeLatch.RunIfNotLatched(() =&gt;\r\n        {\r\n            \/\/ perform data\/view update operations\r\n        });\r\n    }\r\n}<\/pre>\n<p>At first sight I liked the <code>using() { }<\/code> 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 <code>using() { }<\/code> syntax is kind of <em>misused<\/em> and could lead  to irritations because there is implicit knowledge about the internal  functionality of the Latch. Again, the intent is not <em>explicitly<\/em> revealed.<\/p>\n<h3>Latch #2: Boolean Latch<\/h3>\n<p>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:<\/p>\n<pre class=\"brush:csharp\">public class Latch\r\n{\r\n    public bool IsLatched { get; private set; }\r\n\r\n    public void RunLatched(Action action)\r\n    {\r\n        try\r\n        {\r\n            IsLatched = true;\r\n            action();\r\n        }\r\n        finally\r\n        {\r\n            IsLatched = false;\r\n        }\r\n    }\r\n\r\n    public void RunIfNotLatched(Action action)\r\n    {\r\n        if (IsLatched)\r\n            return;\r\n\r\n        action();\r\n    }\r\n}<\/pre>\n<p>Here the basic boolean logic behind matches with  the Disposing Latch, but the syntax has changed. The Latch now contains  two methods. <code>RunLatched()<\/code> executes an action inside the Latch and  prevents actions from being executed in <code>RunIfNotLatched()<\/code>. Here&#8217;s the usage for this Latch type in our example:<\/p>\n<pre class=\"brush:csharp\">public partial class SomeControl : UserControl\r\n{\r\n    \/\/ ...\r\n\r\n    private readonly Latch _textSetByCodeLatch = new Latch();\r\n\r\n    private ViewData _viewData;\r\n    public ViewData ViewData\r\n    {\r\n        get { return _viewData; }\r\n        set\r\n        {\r\n            _viewData = value;\r\n            if (value != null)\r\n            {\r\n                _textSetByCodeLatch.RunLatched(() =&gt;\r\n                {\r\n                    _someTextBox.Text = value.SomeValue;\r\n                });\r\n                \/\/ other operations\r\n            }\r\n        }\r\n    }\r\n\r\n    private void OnSomeTextBoxTextChanged(object sender, EventArgs e)\r\n    {\r\n        _textSetByCodeLatch.RunIfNotLatched(() =&gt;\r\n        {\r\n            \/\/ perform data\/view update operations\r\n        });\r\n    }\r\n}<\/pre>\n<p>Now  the Latch has a cleaner and more explicit syntax. And like the Disposing  Latch it has a clean exception handling mechanism. That&#8217;s the good  news. With that our Boolean Latch is applicable in most simple  scenarios. But not in all! Imagine <em>parallel execution<\/em> of UI actions.  Moreover imagine having two actions which should be run in <code>RunLatched()<\/code> of the same Latch object &#8211; again in parallel:<\/p>\n<ol>\n<li>Action 1 enters <code>RunLatched()<\/code> and the Latch changes its state.<\/li>\n<li>Action 2 enters <code>RunLatched()<\/code>, the Latch state remains in  <code>IsLatched<\/code>.<\/li>\n<li>Action 1 leaves <code>RunLatched()<\/code> and the Latch changes its state to  not latched.<\/li>\n<\/ol>\n<p>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 <code>RunIfNotLatched()<\/code>, which is no  help on the initial problem. This is not only true for the Boolean  Latch, but for the Disposing Latch as well.<\/p>\n<h3>Latch #3: Counting Latch<\/h3>\n<p>This problem is solved by the Counting Latch, which is most similar  to Jeremy&#8217;s Latch implementation. Instead of having just a boolean  discriminator, it employs a counter for parallel <code>RunLatched()<\/code> calls. The  <code>IsLatched<\/code> state is determined based on this counter. If it&#8217;s equal to <code>0<\/code>, the Latch is not latched (because no method is currently running  inside of <code>RunLatched()<\/code>). Else the Latch is treat as latched. Here&#8217;s the  implementation of this Latch variant (edit: thanks nwiersma for the thread-safe <a href=\"http:\/\/www.minddriven.de\/index.php\/technology\/development\/design-patterns\/latch-design-pattern#comment-6208\">hint<\/a>):<\/p>\n<pre class=\"brush:csharp\">public class Latch\r\n{\r\n    private readonly object _counterLock = new object();\r\n\r\n    public int LatchCounter { get; private set; }\r\n\r\n    public bool IsLatched\r\n    {\r\n        get { return (LatchCounter &gt; 0); }\r\n    }\r\n\r\n    public void RunLatched(Action action)\r\n    {\r\n        try\r\n        {\r\n            lock(_counterLock) { LatchCounter++; }\r\n            action();\r\n        }\r\n        finally\r\n        {\r\n            lock(_counterLock) { LatchCounter--; }\r\n        }\r\n    }\r\n\r\n    public void RunIfNotLatched(Action action)\r\n    {\r\n        if (IsLatched)\r\n            return;\r\n\r\n        action();\r\n    }\r\n}<\/pre>\n<p>The  usage in this case is equivalent to the Boolean Latch. You should note that <em>each<\/em> of these Latch implementations works, it&#8217;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.<\/p>\n<h3>Benefits of using the Latch<\/h3>\n<p>Using the Latch for the foresaid problems has clear advantages over the  use of event detach\/attach and boolean flags. First the Latch  <em>encapsulates the logic<\/em> of running actions depending on a state, in this  case the current execution of another action. Thus the purpose of a  Latch is <em>explicit<\/em>, in contrast to the implicit intent of e.g. boolean  flags. This <em>increases code readability<\/em>.<\/p>\n<p>The second advantage  comes with <em>resetting the initial state<\/em>. The Latch performs this task  itself when an action leaves the <code>RunLatched()<\/code> method for example. With  boolean flags and event detach\/attach this is your task. It&#8217;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.<\/p>\n<p>In <strong>conclusion<\/strong> the Latch is a pretty simple design pattern which increases readability  and <em>feels right<\/em> for the problem of dependent action execution. For  myself, at least I&#8217;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.<\/p>\n<p><a href=\"http:\/\/www.dotnetkicks.com\/kick\/?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d968\"><img decoding=\"async\" src=\"http:\/\/www.dotnetkicks.com\/Services\/Images\/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d968\" border=\"0\" alt=\"kick it on DotNetKicks.com\" \/><\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In my first blog post I&#8217;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&#8217;ve shown two simple solutions which are very common in many &hellip; <a href=\"https:\/\/www.minddriven.de\/index.php\/technology\/development\/design-patterns\/latch-design-pattern\" class=\"more-link\"><span class=\"screen-reader-text\">Latch me if you can!<\/span> weiterlesen<\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[12],"tags":[264,263],"class_list":["post-968","post","type-post","status-publish","format-standard","hentry","category-design-patterns","tag-design-pattern","tag-latch"],"_links":{"self":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts\/968","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/comments?post=968"}],"version-history":[{"count":14,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts\/968\/revisions"}],"predecessor-version":[{"id":1012,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts\/968\/revisions\/1012"}],"wp:attachment":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/media?parent=968"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/categories?post=968"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/tags?post=968"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}