我想使用多个线程更新数据表中的单个数据行。这真的可能吗?
我编写了以下代码,实现了一个简单的多线程来更新单个数据行。每次我得到不同的结果。为什么会这样?
public partial class Form1 : Form
{
private static DataTable dtMain;
private static string threadMsg = string.Empty;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Thread[] thArr = new Thread[5];
dtMain = new DataTable();
dtMain.Columns.Add("SNo");
DataRow dRow;
dRow = dtMain.NewRow();
dRow["SNo"] = 5;
dtMain.Rows.Add(dRow);
dtMain.AcceptChanges();
ThreadStart ts = new ThreadStart(delegate { dtUpdate(); });
thArr[0] = new Thread(ts);
thArr[1] = new Thread(ts);
thArr[2] = new Thread(ts);
thArr[3] = new Thread(ts);
thArr[4] = new Thread(ts);
thArr[0].Start();
thArr[1].Start();
thArr[2].Start();
thArr[3].Start();
thArr[4].Start();
while (!WaitTillAllThreadsStopped(thArr))
{
Thread.Sleep(500);
}
foreach (Thread thread in thArr)
{
if (thread != null && thread.IsAlive)
{
thread.Abort();
}
}
dgvMain.DataSource = dtMain;
}
private void dtUpdate()
{
for (int i = 0; i < 1000; i++)
{
try
{
dtMain.Rows[0][0] = Convert.ToInt32(dtMain.Rows[0][0]) + 1;
dtMain.AcceptChanges();
}
catch
{
continue;
}
}
}
private bool WaitTillAllThreadsStopped(Thread[] threads)
{
foreach (Thread thread in threads)
{
if (thread != null && thread.ThreadState == ThreadState.Running)
{
return false;
}
}
return true;
}
}
对此有什么想法吗?
谢谢
NLV