How to prevent my Timer from GC collecting before its callback excuted?

后端 未结 6 668
情深已故
情深已故 2021-01-26 06:51

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);
}
         


        
6条回答
  •  佛祖请我去吃肉
    2021-01-26 07:30

    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.

提交回复
热议问题