Thread-safe DataSet
c#, dataset, thread-safety
Solution
No, it is not safe. You should change your code in:
public sealed class MyDataSet{
public static DataSet ds = new DataSet();
private static object _lock = new object();
public static UpdateRow(key,data)
{
lock(_lock){
DataRow dr = ds.Tables[0].Rows.Find(key);
dr.AcceptChanges();
dr.BeginEdit();
dr["col"] = data;
dr.EndEdit();
}
}
}
Your `_lock` object should be a static object in your program to make it a good lock. And your `Find` should be in the locked part.
Problem
I want to make update operations to the DataTable/DataSet thread-safe. There are ~20 threads each updating ~40 rows of global DataTable using `Rows.Find(pk)` method of DataTable. Each thread will be updating distinct rows of DataTable. I'm using the following wrapper class for DataSet. Is this approach thread-safe? ``` public sealed class MyDataSet{ public static DataSet ds = new DataSet(); public static UpdateRow(key,data) { object _lock = new object(); DataRow dr = ds.Tables[0].Rows.Find(key); lock(_lock){ dr.AcceptChanges(); dr.BeginEdit(); dr["col"] = data; dr.EndEdit(); } } } ``` This method is called from a `for` loop. ``` for(int x=0; x<40; x++;){ if(someCondition) . . . MyDataSet.UpdateRow(key,data); . . . } ``` Everything is done in a multithreaded environment. Is UpdateRow method thread safe?