1

I'm making a service in C#.

I have the functions:

onStart();
copy();
onStop();

I was running copy() inside the onStart() function. But it was making the service status be set to starting forever, since the copy() function is a loop that runs infinitely (with a Thread.Sleep() inside), making the service unstoppable, unless I finish the proccess in Task Manager.

So, question is:

How can I get copy() to run at the end of onStart() and get onStart() not to wait for the completion of copy()?

Phiter
  • 14,570
  • 14
  • 50
  • 84

2 Answers2

2

You can start new Thread from OnStart so that your service return control back service controller.

protected override void OnStart(string[] args)
{
    Thread MyThread = new Thread(new ThreadStart(Starter));
    MyThread.Start();

    base.OnStart(args);
}

private void Starter()
{
   //Add your long running code here
}

You can also use Timer that will be started in OnStart and will keep your service running.

private System.Timers.Timer timer;

protected override void OnStart(string[] args)
{
    this.timer = new System.Timers.Timer(3000);  // 30000 milliseconds = 30 seconds
    this.timer.AutoReset = true;
    this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed);
    this.timer.Start();
 }

 protected override void OnStop()
 {
      this.timer.Stop();
      this.timer = null;
 }

 private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
 {
      //Your code goes here  
 }
Adil
  • 146,340
  • 25
  • 209
  • 204
  • What does the `base.OnStart(args);` do? – Phiter May 04 '16 at 12:41
  • This will pass the argument to base class. – Adil May 04 '16 at 12:43
  • Do you have Starter defined as given in example – Adil May 04 '16 at 12:45
  • Yes. It had parameters, removing them got the error to dismiss. – Phiter May 04 '16 at 12:46
  • Between the thread and timer option, which is best in your opinion? And the timer runs infinitely or just once? Should I put the loop with `Thread.Sleep` inside the `timer_Elapsed`? – Phiter May 04 '16 at 12:51
  • It depends what you want to achieve, Most cases Timer is a better choice. We usually try to achieve similar periodic operation with for loop and sleep. – Adil May 04 '16 at 12:54
  • I've decided to use the Timers solution. I have a quick question: `new System.Timers.Timer(3000)` creates the timer but runs it only after the time period. How can I start it imediately and then run with the interval? – Phiter May 04 '16 at 13:09
  • 1
    [Found it, nevermind](http://stackoverflow.com/questions/6924072/how-to-fire-timer-elapsed-event-immediately) – Phiter May 04 '16 at 13:10
  • I was busy and could not reply. That is good to know that you found the solution. – Adil May 05 '16 at 04:34
0

You can use a new Thread or use a Timer, with the code of an iteration in the Tick event.