C#Windows服务不会触发计时器事件 [英] C# Windows Service Not Firing Timer Event

查看:97
本文介绍了C#Windows服务不会触发计时器事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图在我的Windows服务中运行一个计时器。我通过简单地启动记事本实例来测试下面的计时器代码。所以计时器似乎正在触发,但是当我去插入或更新到db时没有任何反应。任何建议?



I have been trying to run a timer in my windows service. I tested the timer code below by simply starting an instance of notepad. So the timer appears to be firing, but when I go to insert or update to the db nothing happens. Any Suggestions?

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.Net;
using System.Net.NetworkInformation;
using System.Threading;
using System.Globalization;
using System.Timers;
using System.Data.SqlClient;


namespace Monitor
{
    public partial class Service1 : ServiceBase
    {

        public int avg= 28;


        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            //timer1.Interval = 3000;
            timer1.Enabled = true;
            //timer1.Start();
        }

        protected override void OnStop()
        {
            timer1.Stop();
        }


        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
   
                              SqlConnection cs = new SqlConnection(@"Server=130-abcd-P-001.OSdd.LOCAL;Initial Catalog=AIM;User ID=user;Password=password");

                    SqlCommand cmd = new SqlCommand("select * from AIM where computerName='" + 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();
                            }
                        }

                        SqlCommand update = new SqlCommand(@"Update AIM set latency = '" + avg + "', modifiedTime = '" + DateTime.Now + "' where computerName = '" + System.Environment.MachineName + "'", cs);
                        update.CommandType = CommandType.Text;
                        dr.Close();
                        update.ExecuteNonQuery();



                    }
                    else
                    {

                        IPHostEntry host;
                        string localIP = "";
                        host = Dns.GetHostEntry(Dns.GetHostName());
                        foreach (IPAddress ip in host.AddressList)
                        {
                            if (ip.AddressFamily.ToString() == "InterNetwork")
                            {
                                localIP = ip.ToString();
                            }
                        }
                        SqlCommand insert = new SqlCommand(@"Insert into AIM (computerName, latency, stationIP, modifiedTime) values ('" + System.Environment.MachineName + "', '" + avgRtt + "', '" + localIP + "', '" + DateTime.Now + "')", cs);
                        insert.CommandType = CommandType.Text;
                        dr.Close();
                        insert.ExecuteNonQuery();
                        cs.Close();



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

                }
            
        }


    }

推荐答案

Hello Dustin尝试使用此代码:



Hello Dustin try with this code:

private Timer timer1 = null;    //declaration


 protected override void OnStart(string[] args)
  {
    private Timer timer1 = null;
    timer1 = new Timer();
    this.timer1.Interval = Convert.ToDouble(1000); //timer intraval in milliseconds
    this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
    timer1.Enabled = true;

  }

private void timer1_Tick(object sender, EventArgs e)
  {
               //write your code here
  }


你应该在OnElapsedEvent之前有新的东西。

查看此链接获取样本。

http://msdn.microsoft.com/en-us/library/system.timers.timer.elapsed .aspx [ ^ ]
You should have new before OnElapsedEvent.
Check this link for a sample.
http://msdn.microsoft.com/en-us/library/system.timers.timer.elapsed.aspx[^]


参考这个有效的解决方案:







易于学习的窗口服务 [ ^ ]
refer this solution it works:



Easy to learn Window Service[^]


这篇关于C#Windows服务不会触发计时器事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆