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

后端 未结 6 666
情深已故
情深已故 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:24

    It's important to see that GC.KeepAlive() cannot solve your problem. That just extends the lifetime of your object to the statement. You would have to loop or block for as long as the timer needs to stay alive. Also beware that the life time of references in local variables is different in the Debug build. The JIT keeps them life until the end of the method to allow watches to work. Producing tricky "works in debug, doesn't work in release mode" problems.

    You'll have to keep a life reference to the timer object. That's most typically done with a field in a class. Lifetime requirements now pass to the class object, it needs to stay alive for as long as the timer is needed. Not usually a problem. If it is, you'll have to make the reference static.

提交回复
热议问题