c# - Rerun method as soon as it has finished -
right i'm using timer trigger method. how can make service run method has finished?
private timer timer; public service() { initializecomponent(); } protected override void onstart(string[] args) { dosomething(); timer = new timer(); timer.enabled = true; timer.interval = 60000; timer.autoreset = true; timer.start(); timer.elapsed += timer_elapsed; } protected override void onstop() { base.onstop(); } private void timer_elapsed(object sender, elapsedeventargs e) { dosomething(); }
get rid of timer , use recursion:
public service() { initializecomponent(); dosomething(); } private void dosomething() { // code takes while execute // make recursive call self dosomething(); }
edit answer accepted won't work in context of service (actually, execute, service forever stuck in 'starting' status, , generate 1503 error).
here full code service continuously execute method:
using system; using system.collections.generic; using system.componentmodel; using system.data; using system.diagnostics; using system.linq; using system.serviceprocess; using system.text; namespace recursion { public partial class service1 : servicebase { public service1() { initializecomponent(); } system.threading.thread thread; protected override void onstart(string[] args) { system.io.file.writealltext(@"c:\temp\foo.txt", "starting at: " + system.datetime.now.tostring()); thread = new system.threading.thread(dosomething); thread.name = "worker thread"; thread.isbackground = true; thread.start(); } private void dosomething() { while (true) { system.io.file.writealltext(@"c:\temp\foo.txt", "the time now: " + system.datetime.now.tostring()); system.threading.thread.sleep(1000); } } protected override void onstop() { } } }
@cslecours wrong cause stackoverflow, right in causing onstart method not exit cause , error windows service.
Comments
Post a Comment