0

after reading this stack overflow page and this other one.

I didn't really found an answer to my question, I was asking myself why is my service stopping after one loop althought is works fine in debug mode (visual studio).

Here is the code I have

public partial class Service1 : ServiceBase
{
    Timer t;
    // some more stuff

    public Service1()
    {
        InitializeComponent();
        // some more stuff
        t = new Timer();
        t.Interval = 1000 * 5; // timer of 5 secs.
        t.Elapsed += new ElapsedEventHandler(this.onTimer);
        t.Start();
    }

    protected void onTimer(object sender, ElapsedEventArgs args)
    {
        t.Stop(); // stop the timer to prevent callung the function 2 times in parallel
        int tag = 1;
        while (tag == 1)
        {
            tag = doStuff(); // return 1 if it needs to continu looping, return 0 when done
        }
        t.Start();
    }
}

My problem is that doStuff() gets called one time, loop only once, and never get called again (I know this thanks to a log.txt file that I din't show up in the exemple)

Ren
  • 157
  • 12
  • That isn't a windows service. It doesn't extend `ServiceBase`, and it seems to be a UI class (it calls `InitializeComponent`), even though it isn't partial and doesn't extend any base class which might define that method, and doesn't define it itself. I'm very confused about how you're intending to run that code as a service – canton7 Mar 31 '22 at 08:24
  • @canton7 I've writen this bit of code as an exemple and forgot the extend, but it does extend ServiceBase – Ren Mar 31 '22 at 08:38
  • Have you made sure that this example actually reproduces your problem? – canton7 Mar 31 '22 at 08:39
  • Actually no, but I don't see why it would not since it is the "same" exept for the doStuff function that is empty ( my complet program have a db link and a file writer, but it can't interfeer with any of the main logic – Ren Mar 31 '22 at 08:42
  • Well, do that first, otherwise we might waste time trying to debug something which actually works. You're supposed to post a [mcve], the key word being "reproducible" – canton7 Mar 31 '22 at 08:44
  • yeah that s true, let me do this real quick – Ren Mar 31 '22 at 08:45
  • 1
    Well, even stranger, I realised that my full code work fine on my computer, but not on my virtual machine, something to do with the more stuff I didn't show up. I wanted to try finding by myself after this discovery – Ren Mar 31 '22 at 09:47
  • Note, you probably want to be starting your timer from the `OnStart` method, rather than the constructor. Likewise, you will want to use the `OnStop` method to completely stop your service (which will require more than just calling `t.Stop()`, since you might be in the middle of an `onTimer` call when this happens) – canton7 Mar 31 '22 at 09:54

0 Answers0