Windows Service start then stops immediately

15,400

I had this problem and search many hours on google then i find solution. You can add following code in your code. Add InitializeTimer() in your class constructor.You should Set oTimer.Enabled = true and oTimer.Start() on OnStart() and oTimer.Stop() on OnStop().

Code:

  void create()
    {
        string s = "";
    }
    void InitializeTimer()
    {
        oTimer = new System.Timers.Timer(interval);
        oTimer.AutoReset = true;
        oTimer.Enabled = true;
        oTimer.Elapsed += new System.Timers.ElapsedEventHandler(oTimer_Elapsed);
    }

    void oTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        CreateFileData();
    }

    void CreateFileData()
    {
        string path = @"C:\SimpleWcfService\SimpleWindowsService\bin\Release\Singh.txt";
        StreamWriter oStreamWriter = new StreamWriter(path, true);
        oStreamWriter.WriteLine(DateTime.Now.ToString());
        oStreamWriter.Close();
        oStreamWriter = null;
    }
Share:
15,400

Related videos on Youtube

Ricardo Amendoeira
Author by

Ricardo Amendoeira

Updated on July 07, 2022

Comments

  • Ricardo Amendoeira
    Ricardo Amendoeira almost 2 years

    I've created a windows service that creates a Form in which a tool strip icon is created to manage a socket. I'm able to install through an installer created in Visual Studio, but when I go to Services and start my service it gives me an error saying it started and stopped immediately.

    Here's the service code:

    public Service()
        {
            InitializeComponent();
        }
    
        protected override void OnStart(string[] args)
        {
            base.OnStart(args);
    
            ServiceName = "WizardServer";
            CanPauseAndContinue = false;
            CanHandleSessionChangeEvent = true;
            CanStop = true;
    
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
    
            try
            {
                connectionHandler = new ConnectionHandler();  
                serviceThread = new System.Threading.Thread(new ThreadStart(serviceTarget));
                alive = true;
                serviceThread.Start();
            }
            catch {}
        }
    
        private void serviceTarget()
        {
            Application.Run(new Form1(connectionHandler));
    
            while (alive) 
            {
                Thread.Sleep(10000);
            }
        }
    
        protected override void OnStop()
        {
            base.OnStop();
    
            try
            {
                connectionHandler.stop();
            }
            catch {}
    
            serviceThread.Abort();
    
            alive = false;
            Stop();
        }
    

    PS: I've tested the form and it works just fine.