title: C# One Time (Fire once) Events Implementation
body: <p>I'm interested creating an event handling object that you can subscribe for one time execution only and then the action is automatically unsubscribed </p>
  
  <p>Is there similar native functionality in .NET?
  Here is what works for me right now:</p>
  
  <pre><code>public class CustomTimer
  {
      private event Action OneSecond;
  
      private readonly Timer timer;
  
      // Registered actions that should be called only once
      private readonly ICollection&lt;Action&gt; oneOffs;
  
      public CustomTimer()
      {
          this.timer = new Timer { Interval = 1000 };
          this.timer.Elapsed += this.OnOneSecond;
          this.oneOffs = new HashSet&lt;Action&gt;();
      }
  
      public bool IsRunning =&gt; this.timer.Enabled;
  
      public void Start()
      {
          this.timer.Start();
      }
  
      public void Stop()
      {
          this.timer.Stop();
      }
  
      public void Subscribe(Action callback)
      {
          this.OneSecond += callback;
      }
  
      public void SubscribeOnce(Action callback)
      {
          this.oneOffs.Add(callback);
          this.Subscribe(callback);
      }
  
      public void Unsubscribe(Action callback)
      {
          this.OneSecond -= callback;
          this.oneOffs.Remove(callback);
      }
  
      protected virtual void OnOneSecond(object sender, ElapsedEventArgs elapsedEventArgs)
      {
          this.OneSecond?.Invoke();
          this.UnsubscribeOneOffs();
      }
  
      private void UnsubscribeOneOffs()
      {
          if (this.oneOffs.Count &gt; 0)
          {
              foreach (var action in this.oneOffs)
              {
                  this.OneSecond -= action;
              }
  
              this.oneOffs.Clear();
          }
      }
  }
  </code></pre>
  
  <p>Here the events are set to execute every second. </p>
  
  <p>How can I use similar strategy in other object that trigger events unpredictably
  and prevent events execution while the <strong>UnsubscribeOneOffs()</strong> method is running.
  Should I use some kind of lock?</p>