c#winform多线程,lock的问题,用了lock还是提示出错,报错为对象当前正在其他地方使用。
求大神,我一头雾水的搞了半天还是报错,我用一个线程实时显示数据库数据的条数,并调用caption属性实时显示出来,结果在数据改变的时候,鼠标不停的点别的button时会报错。button click事件也是一个数据库查询到gridview事件。代码如下:
public void Thread2()
{
while (true)
{
Thread.Sleep(5000);
int box01 = rowcount("select * from smartbox01");
int inbox01 = box01 - rowcount("select * from smartbox01 where inuse ='借出'");
lock(this) calendarItem.Caption = string.Format("一号工具箱({0}/{1})", inbox01, box01);
// Thread.Sleep(20);
int box02 = rowcount("select * from smartbox02");
int inbox02 = box02 - rowcount("select * from smartbox02 where inuse ='借出'");
lock(this) tasksItem.Caption = string.Format("二号工具箱({0}/{1})", inbox02, box02);
}
}
private void calendarItem_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
{
gridView1.Columns.Clear();
this.xtraTabControl1.SelectedTabPage = xtraTabPage3;
string sql = string.Format("select INUSE as 使用状态,MODEL as 名称,SIZE as 规格,STATE as 工具状态,LOCATION as 地点,DATE as 时间,keyrfid.[USER]as 使用人员 from smartbox01 left join keyrfid on keyrfid.KEYRFID=smartbox01.KEYRFID");
using (SqlConnection conn = new SqlConnection(DBHelper.connstring))
{
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds);
gridControl.DataSource = ds.Tables[0];
gridView1.Columns[5].DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
}
}