c# - Using a timer in a long running windows service -
i trying use timer in windows service. service able start , stop , write event log when happens, works. problem want use timer keeps running , write event log every time timeelapsed event fired.
edit: (i changed code, timer field, still not result expect, no log entries in event log)
using system.timers; initializing service:
public timer timer; public monitorservice() { initializecomponent(); timer = new timer(10000); //some code doesn't matter } the on start event
protected override void onstart(string[] args) { // hook elapsed event timer. timer.elapsed += new elapsedeventhandler(ontimedevent); timer.enabled = true; timer.start(); eventlogger.writeentry("biztalk monitoring service started", eventlogentrytype.successaudit); // if timer declared in long-running method, use // keepalive prevent garbage collection occurring // before method ends. // gc.keepalive(timer); } private int count =0; the on timed event: (this won't work, there no entries written event log every 10 seconds, while expect do)
// specify want happen when elapsed event // raised. private void ontimedevent(object source, elapsedeventargs e) { //some other code doesn't mather count++; eventlogger.writeentry(string.format("timerevent has ran {0} times. total time is: {1}", count, e.signaltime), eventlogentrytype.information); } the on stop event:
protected override void onstop() { eventlogger.writeentry("biztalk monitoring service stopped", eventlogentrytype.warning); } main
for wonder main method in program.cs:
///<summary> ///the main entry point application. ///</summary> static void main() { var servicestorun = new servicebase[] { new monitorservice() }; servicebase.run(servicestorun); } already asked? yes indeed!
i aware of fact question has been asked earlier here: windows service timer , best timer using in windows service
but solutions doesn't seem solve problem.
any suggestions welcome!
you timer local onstart method. should not be. should field of service class, don't need cheat garbage collector using hints.
edit: did not specify usings. make sure using timer using system.timers.timer, not system.windows.forms.timer.
Comments
Post a Comment