Click here to Skip to main content
15,896,382 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have the following code.

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Data.SqlClient;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;
using System.Globalization;
using System.Timers;
using System.IO;
using WindowsService1.ServiceReference1;

namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        public static double infinity = double.PositiveInfinity;
        public static int pingCount = 0;
        public static long avgRtt;
        public static System.Timers.Timer timer1;
        public static System.Timers.Timer timer2;
        public static Service1Client client = new Service1Client();

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {

            timer1 = new System.Timers.Timer();
            timer1.Interval = Convert.ToDouble(3000); //timer intraval in milliseconds
            timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Tick);
            timer1.Enabled = true;

            timer2 = new System.Timers.Timer();
            timer2.Interval = Convert.ToDouble(3000); //timer intraval in milliseconds
            timer2.Elapsed += new System.Timers.ElapsedEventHandler(timer2_Tick);





        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //Latency lat = new Latency();
            //       lat.stationName = "me";
            //       lat.stationip = "myip";
            //       lat.latency = 2;

            //       client.submitData(lat);
            calcLat();
        }
        private void timer2_Tick(object sender, EventArgs e)
        {
            SqlConnection cs = new SqlConnection(@"Server=130-ASQL1-P-001.OSCA.LOCAL;Initial Catalog=AIM;User ID=user;Password=pass");

            SqlCommand cmd = new SqlCommand("select * from NIM_Latency where stationName='" + System.Environment.MachineName + "'", cs);

            cmd.CommandType = CommandType.Text;

            cmd.Connection = cs;

            cs.Open();

            SqlDataReader dr = cmd.ExecuteReader();


            dr.Read();
            if (dr.HasRows)
            {


                IPHostEntry host;
                string localIP = "";
                host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (IPAddress ip in host.AddressList)
                {
                    if (ip.AddressFamily.ToString() == "InterNetwork")
                    {
                        localIP = ip.ToString();
                    }
                }

                Latency lat = new Latency();
                lat.stationName = System.Environment.MachineName;
                lat.latency = avgRtt;
                lat.stationip = localIP;


                
                client.updateData(lat);

                dr.Close();
                pingCount = 0;
                client.Close();
                cs.Close();


            }
            else
            {

                IPHostEntry host;
                string localIP = "";
                host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (IPAddress ip in host.AddressList)
                {
                    if (ip.AddressFamily.ToString() == "InterNetwork")
                    {
                        localIP = ip.ToString();
                    }
                }

                Latency lat = new Latency();
                lat.stationName = System.Environment.MachineName;
                lat.latency = avgRtt;
                lat.stationip = localIP;

                client.submitData(lat);

                pingCount = 0;

                dr.Close();
                cs.Close();
                client.Close();
            }
        }



        protected override void OnStop()
        {
        }

        public void calcLat()
        {
            //client.Open();

            var ping = new Ping();

            var reply = ping.Send("10.209.224.100", 3000);

            avgRtt = (avgRtt * pingCount++ + reply.RoundtripTime) / pingCount;

            pingCount++;

            if (pingCount == 4)
            {
                timer1.Stop();
                timer2.Enabled = true;
            }
        }
    }
}


When I start the service the timer job runs once and then the service stops on it's own. I've been doing research and i'm seeing alot of talk about garbage collector possibly stopping the service. This is my first windows service so any help would be great.
Posted
Updated 5-Jun-13 8:15am
v3

1 solution

This is because you don't really have any code supporting Windows Service work. Typically, OnStart method creates one or more threads which do all the work. The timer may or may not be needed, but it's almost always better and easier to avoid using any.

—SA
 
Share this answer
 
Comments
Dustin Prevatt 3-Jun-13 14:24pm    
i need a task to be completed every 60 seconds..

How can this be done without using a timer. Please give me an example.
Sergey Alexandrovich Kryukov 3-Jun-13 14:28pm    
If depends on what are you trying to achieve with the timer and why. Basically, you create an infinite look with some Thread.Sleep in each iteration. Real time value can be taken from System.Diagnostic.StopWatch or (less accurately, but "absolute" calendar time), with System.DateTime.Now, System.DateTime.UtcNow...
—SA
Dustin Prevatt 3-Jun-13 14:25pm    
if I created a new thread in the OnStart and then called the timer from it would that possibly resolve this?
Sergey Alexandrovich Kryukov 3-Jun-13 14:29pm    
Why timer? What does it mean: "called the timer"?
—SA
Dustin Prevatt 3-Jun-13 14:31pm    
i mean start the timer from the new thread that was created in the OnStart event

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900