c# - System.Timers.Timer enabled and GarbageCollector -



c# - System.Timers.Timer enabled and GarbageCollector -

in project created system.timers.timer object , interval set 10 min. every 10 min getting elapsed event. in event handler executing code.

before executing code setting enabled property equal false because if handler takes longer execute next interval thread executes elapsed event.

problem here elapsed event stopped.

i have read articles , suspecting moment enabled property set false garbagecollector frees timer object.

if right please tell me solution.

below illustration code:

public class timer1 { private static system.timers.timer atimer; public static void main() { // create timer 10 sec interval. atimer = new system.timers.timer(10000); // hook elapsed event timer. atimer.elapsed += new elapsedeventhandler(ontimedevent); // set interval 10min. atimer.interval = 600000; atimer.enabled = true; console.writeline("press come in key exit program."); console.readline(); } private static void ontimedevent(object source, elapsedeventargs e) { atimer.enabled = false; // excutes code atimer.enabled = true; } }

since have field in class pointing timer object, gc not collect timer object.

but code may raise exception, , can prevent enabled property become true again. guard agianst this, should utilize finally block:

private static void ontimedevent(object source, elapsedeventargs e) { atimer.enabled = false; seek { // excutes code } catch(exception ex) { // log exception , perchance rethrow // attention: never swallow exceptions! } { atimer.enabled = true; } }

c# .net timer garbage-collection

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -