c# - 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;
}
解决方案
推荐阅读
- jenkins - Jenkins 管道中未使用自定义记录器
- javascript - typeerror 无法读取未定义的属性“currenttarget”
- asp.net - JSON.NET 错误“无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型,因为该类型需要 JSON 对象(例如 {"name":"value"})"
- str-replace - php的str_replace函数中count参数是什么意思?如何使用它?
- javascript - 复选框过滤器/搜索按钮:未选中时无法撤消过滤
- php - 调度程序 runInBackground 在 laravel 5.4 中不起作用
- xml - Odoo 10:布尔字段旁边的输入字段
- sql - 将 SSIS 参数传递给 OPENQUERY
- android - 如何在单独的 UI 活动中检索 Firebase 任务结果
- python - 使用 Python 和 Node.js 在 Heroku 中导入 psycopg2