gpt4 book ai didi

.net - DataRow线程安全吗?如何使用多个线程更新数据表中的单个数据行? -.net 2.0

转载 作者:行者123 更新时间:2023-12-03 13:22:26 24 4
gpt4 key购买 nike

我想使用多个线程更新数据表中的单个数据行。这实际上可行吗?

我编写了以下代码,实现了一个简单的多线程来更新单个数据行。每次我得到不同的结果。为什么会这样呢?

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;
}


}

有什么想法吗?

谢谢

净现值

最佳答案

根据MSDN:

This type is safe for multithreaded read operations. You must synchronize any write operations.



因此,由于您要更新 DataRowDataTable对象,因此需要使用某种形式的同步来确保您的代码是线程安全的。

顺便说一句,您也不应在用户界面线程中调用 Thread.Sleep或进行繁忙的循环。否则,UI将完全无响应,直到所有线程执行完毕。取而代之的是,您应该在UI上显示某种进度条(或只是一个微调器),可以选择通过线程中的事件进行更新。 BackgroundWorker类是专门为使您的工作更轻松而设计的,因此您可能需要考虑使用它。

关于.net - DataRow线程安全吗?如何使用多个线程更新数据表中的单个数据行? -.net 2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2629122/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com