Is Parallel.forEach(DataTable.AsEnumerable() thread safe

荒凉一梦 提交于 2020-01-02 10:03:58

问题


when used as follows

Parallel.ForEach(DataTable.AsEnumerable(), dr => {

    string str = dr["field1"].ToString();
     //.... other stuff
    dr["f1"] = o.A;
    dr["f2"] = o.B;
    dr["f3"] = o.C;

});

where each thread works on its own datarow

I would assume not but but there's this saying about assumptions....


回答1:


The documentation of the DataRow class definitively states that

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

Can't get any more specific than that.

In any case, parallel writing to a Datatable is probably not going to scale well. Scalability suffers when you have multiple threads accessing shared state and a single datatable is quite obviously shared state. What's more, unless you work with NUMA hardware your CPU cores will contend for access to the same memory bus.

A much better solution is to return any results from the parallel processing (the "other stuff" ) in a separate structure (e.g. one of the concurrent collections) and apply the changes from a single thread when the loop finishes.

Another option is to use PLINQ to calculate the results and and iterate over them with a simple foreach to apply the changes back to the DataTable.

An even better solution would be to discard the original datatable entirely and return a new object that contains the fields you require. Unless your code requires the result to be a DataTable, you could simply return the results as an IEnumerable




回答2:


DataTable is not thread safe for write operations. When you concurrently change rows you will be changing the state of the DataTable hence this will cause problems.




回答3:


If any of those columns are indexed, it is definitely unsafe.
If not, it might be safe, but I don't think so.



来源:https://stackoverflow.com/questions/9297249/is-parallel-foreachdatatable-asenumerable-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!