请教多线程进行数据库更新
这个是我写的代码,可是执行程序会卡死
private void button4_Click(object sender, EventArgs e)
{
Random rnd = new Random();
try
{
using (SqlConnection conn = DBOper.CaertConn("UserDB"))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
for (int i = 1; i <= 100000; i++)
{
cmd.CommandText = string.Format("update dbo.AccountsInfo set FaceID = {0} where UserID ={1}", rnd.Next(1, 29), i);
cmd.ExecuteNonQuery();
}
conn.Close();
}
MessageBox.Show("更新完成!");
}
catch (Exception)
{
MessageBox.Show("更新失败!");
}
}
麻烦大家教教我 怎么用多线程解决啊?麻烦给出实际代码,我对多线程完全不了解,谢谢 --------------------编程问答-------------------- for (int i = 1; i <= 100000; i++)
{
cmd.CommandText = string.Format("update dbo.AccountsInfo set FaceID = {0} where UserID ={1}", rnd.Next(1, 29), i);
cmd.ExecuteNonQuery();
}
要不加上sleep,另外可以每10000个更新组织成一个串,调用一次写库。 --------------------编程问答-------------------- ThreadPool.QueueUserWorkItem(new WaitCallback(Write),null);
public void Write(Object obj)
{
using (SqlConnection conn = DBOper.CaertConn("UserDB"))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
for (int i = 1; i <= 100000; i++)
{
cmd.CommandText = string.Format("update dbo.AccountsInfo set FaceID = {0} where UserID ={1}", rnd.Next(1, 29), i);
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
--------------------编程问答-------------------- 顶顶顶···我是希望多线程来做啊··· --------------------编程问答-------------------- 帮你顶顶
学习一下
--------------------编程问答--------------------
我试验了下···我改成这样了就还是卡死,因为我要弹出一个窗体提示
ShowState ss = new ShowState();
ss.ShowDialog();
ThreadPool.QueueUserWorkItem(new WaitCallback(UpdateAllFace), null);
ss.Close();
--------------------编程问答-------------------- 用BackgroundWorker控件,把执行的代码放到其中的DoWork事件中 --------------------编程问答--------------------
new Thread(() =>
{
Random rnd = new Random();
try
{
using (SqlConnection conn = DBOper.CaertConn("UserDB"))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
for (int i = 1; i <= 100000; i++)
{
cmd.CommandText = string.Format("update dbo.AccountsInfo set FaceID = {0} where UserID ={1}", rnd.Next(1, 29), i);
cmd.ExecuteNonQuery();
}
conn.Close();
}
MessageBox.Show("更新完成!");
}
catch (Exception)
{
MessageBox.Show("更新失败!");
}
}).Start();
补充:.NET技术 , C#