wait - Better way to constantly run function periodically in C# -
i have c# program checking new additions online db. have code have check every 10 seconds
static void main(string[] args) { boolean run = true; while (run) { dbconnect db = new dbconnect(); // amazing awesome mind blowing cool stuff db.closeconnection(); // wait 10 seconds int wait = 10 * 1000; system.threading.thread.sleep(wait); } }
i have error reporting posts db , if major error occurs program shuts down. outside of specific errors within function, method secure , efficient?
you should rewrite program windows service, way not need rely on user logged program run.
if go service route, swap out infinite loop timer.
public partial class service1 : servicebase { public service1() { initializecomponent(); int wait = 10 * 1000; timer = new timer(wait); timer.elapsed += timer_elapsed; // don't want timer start ticking again till tell to. timer.autoreset = false; } private system.timers.timer timer; protected override void onstart(string[] args) { timer.start(); } void timer_elapsed(object sender, elapsedeventargs e) { try { dbconnect db = new dbconnect()) try { // amazing awesome mind blowing cool stuff } { db.closeconnection(); //we put in block still happen, if exception thrown. } timer.start(); } catch(somenoncriticalexception ex) { myexecptionlogger.log(ex, level.waring); //log exception know went wrong timer.start(); //start timer next loop } catch(exception ex) { myexecptionlogger.log(ex, level.critical); //log exception know went wrong this.stop(); //stop service } } protected override void onstop() { timer.stop(); } }
Comments
Post a Comment