Windows服务增加了高CPU使用率

时间:2019-02-14 01:52:03

标签: c# service windows-services

我创建了一个 windows服务,该服务会将数据从 Biometrics 保存到数据库。

我使用 Mysql 作为数据库,然后使用 ZKTeco 作为 Biometrics 。为了从生物识别技术中获取数据,我使用了 dll 。但是,主要问题是该服务将其高CPU使用率从0.01%增加到30-50%,除非我按下Stop然后再次运行,否则服务不会下降。

我尝试将thread.sleep放在其中,在大多数情况下是解决方案,但不能解决我的问题,我使用backgroundworker,因为它可以最大限度地减少cpu的使用而不是使用计时器。

我该如何解决或修复HIGH Cpu?我尝试了thread.sleep(5000 5秒,thread.sleep(1000) 1秒,最后thread.sleep(10)没用

 private void sendata()
    {
        try
        {
            //fetch db parameter by inifile
            _Host = _inifile.ReadSetting("Database Connection", "Host", 5000, "");
            _User = _inifile.ReadSetting("Database Connection", "User", 5000, "");
            _Port = _inifile.ReadSetting("Database Connection", "DBPort", 5000, "");
            _DBname = _inifile.ReadSetting("Database Connection", "Name", 5000, "");

            //Data from Biometric
            ICollection<MachineInfo> lstMachineInfo = manipulator.GetLogData(objZkeeper, int.Parse(MachineNo));

            //MySQL Connection
            connectionString = @"server=" + _Host + @";user id=" + _User + @";port=" + _Port + @";password=hj^yr490Tweh@ty4;database=" + _DBname + @";Min Pool Size=5;Max Pool Size=100;";

            //Connection Starts
            using (var con = new MySqlConnection(connectionString))
            {

                con.Open();
                var cmd = con.CreateCommand();
                var cmdid = con.CreateCommand();

                cmd.CommandText ="set foreign_key_checks=0;CREATE TABLE IF NOT EXISTS `z_log`(`log_id` INT(11) NOT NULL AUTO_INCREMENT ,`machine_id` VARCHAR(50) NOT NULL,`subscription` VARCHAR(50) NOT NULL,`branch_id` VARCHAR(50),`user_id` VARCHAR(50),`datetime` VARCHAR(255),`checktype` VARCHAR(50),`accesstoken` VARCHAR(50),`status` VARCHAR(50) ,PRIMARY KEY (`log_id`),UNIQUE(`datetime`))ENGINE =INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1 COMMENT='List of ID type'";
                cmd.ExecuteNonQuery();


                //Get todays data
                var result = lstMachineInfo.ToList().Where(a => a.datetime > DateTime.Now).ToList();

                //fetch todays data
                foreach (var data in result)
                {
                    //Check last id
                    cmdid.CommandText =
                        "SELECT IF(COUNT(*)=0,0,(SELECT log_id FROM `z_log` ORDER BY log_id DESC LIMIT 1)) AS `ID` FROM z_log;";
                    var drd = cmdid.ExecuteReader();
                    while (drd.Read())
                    {
                        counts = Convert.ToInt32(drd["ID"].ToString()) + 1;
                        Thread.Sleep(10);
                    }
                    drd.Close();

                   //save data where userid & datetime are not duplicate
                    string inserquery =
                        "INSERT IGNORE Into z_log(log_id,machine_id,subscription,branch_id,user_id,datetime,checktype,accesstoken,status)VALUES(" +
                        "@logid,@id,@subs,@branch,@user,@date,@check,@token,@status);";


                    cmd = new MySqlCommand(inserquery, con);
                    cmd.Parameters.AddWithValue("@logid", counts);
                    cmd.Parameters.AddWithValue("@id", data.MachineNumber);
                    cmd.Parameters.AddWithValue("@subs", Subscription.ToString());
                    cmd.Parameters.AddWithValue("@branch", BranchID.ToString());
                    cmd.Parameters.AddWithValue("@user", data.IndRegID);
                    cmd.Parameters.AddWithValue("@date", data.DateTimeRecord);
                    cmd.Parameters.AddWithValue("@check", data.InOut);
                    cmd.Parameters.AddWithValue("@token", AccessToken.ToString());
                    cmd.Parameters.AddWithValue("@status", "0");
                    cmd.ExecuteNonQuery();
                    Thread.Sleep(10);
                }
                con.Close();
            }

        }
        catch (Exception ex)
        {
            Errorlogs(ex.ToString());
        }
    }

//Onstart
protected override void OnStart(string[] args)
      {
         ReadIni();
         ZKBack.RunWorkerAsync();
      }

//Do Work
private void ZKBack_DoWork(object sender, DoWorkEventArgs e)
    {
        try
        {   
            //If device is not connected will connect
            if (isDeviceConnected == false)
            {
                Connect();

            }
            //if connected will get data
            else
            {
                sendata();
            }

        }
        catch (Exception ex)
        {
            Errorlogs(ex.ToString());
        }
    }

 private void ZKBack_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        Thread.Sleep(10);
        ZKBack.RunWorkerAsync();
    }

1 个答案:

答案 0 :(得分:0)

您要在这里完成什么?间隔运行此数据过程?顺便说一句,我已经使用了计时器,但我发现它们并没有占用很多CPU。我想知道您是否通过在RunWorkerCompleted事件中运行RunWorkerAsync在这里创建循环模式。我还将摆脱那些Thread.Sleep(s)。

private void ZKBack_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    Thread.Sleep(10);
    ZKBack.RunWorkerAsync();
}