首页 > 解决方案 > When I can't reach Mysql server ip, winform GUI freezes

问题描述

I am working on a project about data acquisition. I get data via RasPi3b+ from machines. Data is held Mysql on Raspi server. To track data, I have made a dashborad by using C# winforms. Sometimes machines are shut down and I can't reach Mysql server. When that happens winforms freezes. I don't want it to freeze (maybe a green indicator turns red but it should not affect GUI ). How can I fix this ?

This is my timer code that is triggered every 2 second.

 private void timer1_Tick(object sender, EventArgs e)
    {
        for (int i = 0; i < (IpAndNames.Count ); i++)
        {
            string today = DateTime.Now.ToString("yyyy-MM-dd");
            _lblListOpen[i].Text = "open: " + _machineDal.SpenTime(today, IpAndNames[i].Ip, "Logs", "Machine","open").ToString();
            _lblListClose[i].Text = "close: " + _machineDal.SpendTime(today, IpAndNames[i].Ip, "Logs", "Machine","close").ToString();

            string lastState = _machineDal.LastDateAndState(IpAndNames[i].Ip, "Machine", "Logs").LastState;
            DateTime lastTime = _machineDal.LastDateAndState(IpAndNames[i].Ip, "Machine", "Logs").LastDate;

            TimeSpan spendTime= DateTime.Now - lastTime;
            _lblListWorkingTime[i].Text = lastState +" "+ spendTime.ToString("h'h 'm'm 's's'");

        }
    }

This is my data layer code

 public TimeSpan SpendTime(string date, string ip, string tableName, string db, string state)
    {
        TimeSpan openTime= new TimeSpan(0, 0, 0);
        string connString = "server=" + ip + ";user=root;database=" + db + ";port=3306;password=root;Connection Timeout=1";
        try
        {
            using (_conn = new MySqlConnection(connString))
            {
                string query = "SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(time ) ) ) AS timeSum FROM " + tableName + " " +
                "WHERE Laststate='" + state + "' " +
                "and date like \"" + date + "%\"";
                using (MySqlCommand cmd = new MySqlCommand(query, _conn))
                {
                    _conn.Open();
                    using (MySqlDataReader reader = cmd.ExecuteReader())
                    {
                        reader.Read();
                        if (!reader.IsDBNull(0))
                        {
                           openTime= reader.GetTimeSpan(0);
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
        return openTime;
    }

标签: c#mysqlwinformsuser-interfacefreeze

解决方案


推荐阅读