日期:2014-05-20  浏览次数:20920 次

windows service 一次写入两条相同数据的问题!!
如题:我写了一个windows service,往数据库中自动写入指定数据。但是总是发现一次写入两条相同数据。是为什么呢?

代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Xml;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Timers;

namespace WindowsService1
{
  public partial class gzjh : ServiceBase
  {


  public gzjh()
  {
  InitializeComponent();
  }

  protected override void OnStart(string[] args)
  {
  // TODO: 在此处添加代码以启动服务。
  timer1.Interval = 1 * 60 * 1000;
  timer1.Enabled = true;
  timer1.Elapsed +=new ElapsedEventHandler(timer1_Elapsed);
   
  }

  protected override void OnStop()
  {
  // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
  timer1.Enabled = false;
  }

  private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
  {
  timer1.Enabled = false;
  string strconn = "user id=sa;password=123456;Database=wpdb;server=db";
  string strcomm = "insert into sysplan (djh,fbr,jsr,zt) values ('SYS20090720001','SYSTEM','SYSTEM','0')";
  SqlConnection sqlconn = new SqlConnection(strconn);
  sqlconn.Open();
  SqlCommand sqlcomm = new SqlCommand(strcomm, sqlconn);
  SqlDataReader sdr = sqlcomm.ExecuteReader();
  sqlconn.Close();
  timer1.Enabled = true;
  }

  }
}


------解决方案--------------------
C# code

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Diagnostics; 
using System.ServiceProcess; 
using System.Text; 
using System.Xml; 
using System.Data.Sql; 
using System.Data.SqlClient; 
using System.Timers; 

namespace WindowsService1 
{ 
    public partial class gzjh : ServiceBase 
    { 

        public System.Timers.Timer serviceTimer1 = new System.Timers.Timer();//定时器

        public gzjh() 
        { 
            
            serviceTimer1.Elapsed += new System.Timers.ElapsedEventHandler(serviceTimer1_Elapsed);

            InitializeComponent(); 
        } 

        void serviceTimer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            string strconn = "user id=sa;password=123456;Database=wpdb;server=db"; 
            string strcomm = "insert into sysplan (djh,fbr,jsr,zt) values ('SYS20090720001','SYSTEM','SYSTEM','0')"; 
            SqlConnection sqlconn = new SqlConnection(strconn); 
            sqlconn.Open(); 
            SqlCommand sqlcomm = new SqlCommand(strcomm, sqlconn); 
            SqlDataReader sdr = sqlcomm.ExecuteReader(); 
            sqlconn.Close(); 
        }

        protected override void OnStart(string[] args)
        {
            serviceTimer1.Interval = 1 * 60 * 1000;
            serviceTimer1.Enabled = true;
        }

        protected override void OnStop()
        {
            serviceTimer1.Enabled = false;
        }
    }
}