我用C# winform编的程序,采用定时器循环执行线程存储数据到SQL server,定时器1s执行一次。为什么程序运行一段时间后,数据就不能连续存储数据到数据库了,偶尔还能存储到数据库一次,但是线程是一直在循环执行,因为偶尔存储的数据能看到index_ID是变化挺大的。
??
代码如下:
private void timer_SQL_Tick(object sender, EventArgs e)
{
Thread AcceptThd1 = new Thread(new ThreadStart(write_SQL));
AcceptThd1.Start();
}
private void write_SQL()
{
index_ID = index_ID + 1;
string index_ID_S = index_ID.ToString();
try
{
Conn = new SqlConnection(connString_Conn);//实例连接对象
Conn.Open();//打开数据库连接
if (Conn.State == ConnectionState.Open)
{
SqlCommand sqlCmd = new SqlCommand("insert into * values( '" + DateTime.Now.ToString() + "','" + index_ID_S + "')", Conn);
sqlCmd.ExecuteNonQuery();
}
}
catch (Exception ee)
{
}
finally
{
if (Conn.State != ConnectionState.Closed)
{
Conn.Close();
}
}
}