DataTable多线程写不安全
如下代码:
class test
{
private DataTable ftable;
public test()
{
ftable = new DataTable();
DataColumn col = new DataColumn("COL_1", typeof(int));
ftable.Columns.Add(col);
col = new DataColumn("COL_2", typeof(int));
ftable.Columns.Add(col);
for (int i = 1; i < 100; i++)
{
DataRow row = ftable.NewRow();
row["COL_1"] = i;
row["COL_2"] = i * 2;
ftable.Rows.Add(row);
}
}
public void AddColTest()
{
DataColumn col = new DataColumn("COL_Test", typeof(int));
ftable.Columns.Add(col);
Parallel.For(0, ftable.Rows.Count, (index) =>
{
Thread.Sleep(500);
DataRow row = ftable.Rows[index];
row["COL_Test"] = Convert.ToInt32(row["COL_1"]) + Convert.ToInt32(row["COL_2"]);
});
}
public void ShowTable()
{
for(int index = 0; index < ftable.Rows.Count; ++index)
{
DataRow row = ftable.Rows[index];
Console.WriteLine(String.Format("{0} \t\t {1} \t\t {2}", row["COL_1"], row["COL_2"], row["COL_Test"]));
}
}
}
class Program
{
static void Main(string[] args)
{
test t = new test();
t.AddColTest();
t.ShowTable();
Console.ReadKey();
}
}
我本来以为虽然DataTable不是线程安全的… 但是我并没有对任何一个数据做增删…我只是修改了现有单元格的值…理应不会出现任何问题…DataTable应该是已经分配好的内存…
结果现实还是给了我一记响亮的耳光…程序运行失败了… 运行的时候,在这一句row[“COL_Test”] = Convert.ToInt32(row[“COL_1”]) + Convert.ToInt32(row[“COL_2”]);随机抛出一个异常,说索引错误…
具体原因我也不知道为什么会是索引错误… 但是如果把这段关键代码改改,就可以运行很正常了…
Parallel.For(0, ftable.Rows.Count, (index) =>
{
Thread.Sleep(500);
lock(ftable)
{
DataRow row = ftable.Rows[index];
row["COL_Test"] = Convert.ToInt32(row["COL_1"]) + Convert.ToInt32(row["COL_2"]);
}
});