title: C#: How to implement keep alive timers for many objects in a proper and efficient way?
body: <p>What I want to realize is easily explained, but because there are so many different possibilities I'm not really aware of the pro and cons for each possible approach:</p>
  <p>In my application there are plenty (say some thousands of communication objects).
  When such object is idle for some while (meaning that certain methods are not called), it shall simply be closed (what this means in detail is not relevant here).</p>
  <p>I'm thinking of a &quot;timer&quot;, associated with each object, which is re-triggered every time I &quot;use&quot; the object. Like:</p>
  <pre><code>public void ReTrigger()
  {
      lock (_some_locking)
      {
              //Reset the timer
              _timer.Stop();
              _timer.Start();
          }
      }
  }
  </code></pre>
  <p>Note, my application is heavily using async/await and I would like to use a solution which fits best into this concept. I want to avoid a lot of additional threads just for running a lot of timers.</p>
  <p>There are many different timers available:</p>
  <pre><code>System.Timers.Timer
  System.Threading.Timer
  System.Windows.Forms.Timer
  System.Web.UI.Timer
  System.Windows.Threading.DispatcherTimer
  </code></pre>
  <p>So, which one &quot;fits&quot; best into my concept of using asyncio ?</p>
  <p>To put an alternative, would it be better to rely on a background task like</p>
  <pre><code>while (true)
  {
       try
       {
          await Task.Delay(timeout, _cancellationToken)
          ... some action when expired ...
       }
       catch (TaskCanceledException)
       {
          // we have been re-triggered by &quot;using&quot; the object
       }
  }
         
  </code></pre>
  <p>This fits better in my concept, however, in this case I need a new cancellation token after each re-trigger, which is not really nice.</p>
  <p>What is the &quot;golden way&quot; way to solve my problem; preferably using async tasks?</p>
  <p>Another solution would be a housekeeping task, which cyclically polls all active objects for being expired or not. This would work with just one running timer, but is also not very nice.</p>