If I update a DataRow, am I blocking the entire DataTable or just a DataRow?

Suppose I access a DataTable from multiple threads. If I want to access a specific line, I suspect that I need to block this operation (I could be wrong about this, but at least I know that I am so safe):

 // this is a strongly-typed table OrdersRow row = null; lock (orderTable.Rows.SyncRoot) { row = orderTable.FindByOrderId(myOrderId); } 

But then, if I want to update this row, should I lock the table (or rather, the Rows.SyncRoot object) again , or can I just lock the row?

+7
c # thread-safety datatable datarow
source share
3 answers

Actually, just doing lock in one place in a DataTable or DataRow does virtually nothing. An important aspect to remember when using Monitor locks (which is a lock block) is that locking an object does nothing for it; One of the reasons some proponents use dedicated blocking objects rather than blocking the resource itself is because it makes you realize that you need to lock (and on the same object) whenever you deal with the resource.

This means that it is best to lock the entire DataTable , since the data store itself ( DataRow objects internally contain only an offset in the DataTable relative to where to retrieve data), because of this, even if you synchronize access to individual rows, updating two different rows at the same time will cause you to update the same storage engine in an unsynchronized manner.

There is a conflict between viewing internal types as a β€œblack box” and blocking only what you need (which in this case will lead to an erroneous termination of only line blocking) and trying to get an idea of ​​the internal type workings and relying on implementation details that may to change.

The result is that right now you should lock the entire DataTable to avoid updating the internal storage in an unsynchronized way .

+5
source share

you do not need to block reading - only for writing / updating. block the minimum amount you can to ensure data consistency ... usually only one row that you update. if you are updating the relationship between parents and children between tables, you need to lock each row in each table.

+3
source share

This method is safe only for operations with multiple threads:

http://msdn.microsoft.com/en-us/library/system.data.datatable.aspx

http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/11b69e1a-ad6c-48d5-8e14-264af5b0692e

When reading information about data, there is conflicting information about the possibility of locking the table and allows you to safely update data in a row. According to the second link, you can lock the table and update the row. Since this is from MS MVP, I would say that you can probably lock the table and be fine.

+3
source share

All Articles