title: Run code only once using dispatcher
body: <p>I have a simple pattern to run code only once. It's mostly used to Update something on the UI, while it may change very often in the Background.</p>
  
  <pre><code>private bool _updating;
  private void UpdateSomething()
  {
      if (!_updating)
      {
          _updating = true;
  
          Application.Current.Dispatcher.BeginInvoke(new Action(() =&gt;
              {
                  _updating = false;
                  DoSomething();
              }), DispatcherPriority.Background);
      }
  }
  </code></pre>
  
  <p>I would prefer to put the boilerplate code inside a simple method:</p>
  
  <pre><code>public static void RunOnce(Action action, ref bool guard)
  {
      if (!guard)
      {
          guard = true;
  
          Application.Current.Dispatcher.BeginInvoke(new Action(() =&gt;
              {
                  guard = false;
                  action();
              }), DispatcherPriority.Background);
      }
  }
  </code></pre>
  
  <p>und call it like this:</p>
  
  <pre><code>void UpdateSomething()
  {
      RunOnce(DoSomething, ref _updating);
  }
  </code></pre>
  
  <p>However, this does not work as you cannot have ref parameters inside anonymous methods.
  Is there any workaround, e.g. to pin the ref parameter and free it when the method was executed?</p>