I need to create a bunch of timer as local variable to do something like:
void Foo() { Timer t = new Timer(myTimerCallback,null,1000,Timeout.Infinite); }
Unfortunately, some of them are collected by GC before them invoke myTimerCallback after 1 second. Since I have so many Timers, it’s impossible to store them in private static member. And it’s also hard to find a place to put GC.Keeplive(t).
How can I make each timer to do their thing before dying?
You can store them in a collection to keep a reference and in the event method remove the reference from the collection. I think you need to use the state parameter to identify the timer in the collection (pass a reference to the timer or a key in the collection as state parameter in the ‘new timer’ statement).
Please note that the callback functions are executed on other threads, so you will/may have multiple callback functions running simultaneously. Use locking to ensure that adding/removing references is done safely.