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:
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).
I'm thinking of a "timer", associated with each object, which is re-triggered every time I "use" the object. Like:
public void ReTrigger()
{
lock (_some_locking)
{
//Reset the timer
_timer.Stop();
_timer.Start();
}
}
}
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.
There are many different timers available:
System.Timers.Timer
System.Threading.Timer
System.Windows.Forms.Timer
System.Web.UI.Timer
System.Windows.Threading.DispatcherTimer
So, which one "fits" best into my concept of using asyncio ?
To put an alternative, would it be better to rely on a background task like
while (true)
{
try
{
await Task.Delay(timeout, _cancellationToken)
... some action when expired ...
}
catch (TaskCanceledException)
{
// we have been re-triggered by "using" the object
}
}
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.
What is the "golden way" way to solve my problem; preferably using async tasks?
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.