如何使用mysql query
执行2 ThreadingTimer
?我希望db和2nd计时器中的第一个计时器更新数据计算更新的数据量,并以windows格式显示在标签中。这是我的代码,
void PrepareTimers(List<int> _dataValues)
{
foreach (int dataValue in _dataValues)
{
timer = new ThreadingTimer (new TimerCallback(TimerAction), dataValue, 0, 2000);
timer1 = new ThreadingTimer(new TimerCallback(TimerAction1), dataValue, 0, 2000);
//Console.WriteLine("Timer " + dataValue + " created.");
}
}
void TimerAction(object flag)
{
//Console.WriteLine("Timer start "+ flag.ToString());
string myconstring = "SERVER=localhost;" + "DATABASE=alicosms;" + "UID=root;" + "PASSWORD=;";
MySqlConnection mycon = new MySqlConnection(myconstring);
string u = "UPDATED";
mycon.Open();
//Console.WriteLine("Timer " + flag.ToString() + " : " + "UPDATE sms_data_bankasia set flag= @flag * 2 , sendingstatus = '" + u + "' WHERE flag = " + flag.ToString() + " LIMIT 1");
MySqlCommand cmd = new MySqlCommand("UPDATE sms_data_bankasia set flag= @flag * 2 , sendingstatus = '" + u + "' WHERE flag = " + flag.ToString() + " LIMIT 1", mycon);
MySqlParameter param = new MySqlParameter();
param.ParameterName = "@flag";
param.Value = flag;
cmd.Parameters.Add(param);
cmd.ExecuteNonQuery();
mycon.Close();
}
void TimerAction1(object flag)
{
string myconstring = "SERVER=localhost;" + "DATABASE=alicosms;" + "UID=root;" + "PASSWORD=;";
MySqlConnection mycon = new MySqlConnection(myconstring);
string sql = "SELECT count(flag) FROM sms_data_bankasia where sendingstatus='UPDATED' group by flag";
MySqlCommand comd = mycon.CreateCommand();
comd.CommandText = sql;
mycon.Open();
MySqlDataReader dtr = comd.ExecuteReader();
try
{
while (dtr.Read())
{
dict[timer] = label;
dict[timer].Text = dtr[0].ToString() + " program Updated";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
mycon.Close();
}
提供error,"cross thread operation not valid".
我该怎么办?有什么好建议吗?
答案 0 :(得分:0)
在Windows窗体中,除了UI线程之外,您无法在UI中执行任何其他操作。 您的计时器正在单独的线程上运行您的代码。
您可以尝试使用System.Windows.Forms.Timer
,因为它会将事件处理编组回给您的UI线程。
答案 1 :(得分:0)
Here you can read about the solution
只是为了测试它是否修复了你的问题,试着用这样的代码包装你的MessageBox调用:
public delegate void StringDelegate(string message);
private void ShowMessageBox( string message )
{
if (this.InvokeRequired)
{
this.Invoke( new StringDelegate( ShowMessageBox, new object[] { message } ));
return;
}
MessageBox.Show( message );
}
这部分是从记忆中写的,所以它可能会有所不同。