Saturday, 15 August 2015

c# - GC.KeepAlive() and System.Timers.Timer -



c# - GC.KeepAlive() and System.Timers.Timer -

i have declered system.timers.timer object in class level , created in constructor.started timer in method.

in elapsed event handler enabled property set false , excute code , 1 time again enabled set true.

i getting elapsed events each intervel. problem aftre time elapsed stoped.

i suspecting timer object collected gc @ momment enabled property set false in elapsed event hanler eventhadler.

so want timer object set maintain alive.

where should declare gc.keepalive(timer) in project?

if timer declared @ class level, it's not beingness collected automatically gc, because doesn't go out of scope. , setting enabled false can't cause behavior describe. problem somewhere else.

i suspect exception in event handler. system.timers.timer swallows exceptions occur in event handler, meaning if exception escapes event handler, you'll never know it.

i suspect code written similar this:

mytimer.enabled = false; // stuff here mytimer.enabled = true;

if exception thrown during "do stuff here", exception escapes handler, timer never gets re-enabled, , timer code swallows exception never know happened.

you should write event handler this:

mytimer.enabled = false; seek { // stuff here } grab (exception ex) { // handle exceptions } { mytimer.enabled = true; }

you want grab specific exceptions--the ones know how handle. catching exceptions above bad practice.

c# garbage-collection

No comments:

Post a Comment