在 C# 中使数据集线程安全线程、安全、数据

2023-09-06 04:58:05 作者:背对阳光

使数据集在写入时线程安全的最佳模式是什么?

What's the best pattern for making datasets threadsafe on write?

我可以通过谷歌搜索找到最好的方法是'实现一个带锁的包装层',但乍一看这似乎相当混乱.

The best I can find by googling is 'implement a wrapper layer with locks' but at first blush this seems rather messy.

有人可以推荐/指出一个好的解决方案的方向吗?这似乎是一个已经在某个地方解决的问题.

Can someone recommend / point me in the direction of a good solution to this? It seems likely to be a problem that has already been solved somewhere.

我还需要将数据集绑定到 ui 网格,这使事情有些复杂.

edit: I also need to bind the dataset to a ui grid, which complicates matters somewhat.

推荐答案

实现一个带锁的包装层"是要走的路.

"Implement a wrapper layer with locks" is the way to go.

包装层可能会使用特定于您的应用程序使用数据集的方式的锁定.

The wrapper layer will likely use locking that is specific to the way your application uses the DataSets.

尝试为像 DataSet 这样复杂的类设计通用解决方案可能注定要失败.

Attempting to design a generic solution for a class as complex as a DataSet is probably doomed to failure.

例如,枚举属性通常不是线程安全的 - 因此,只要任何调用者枚举许多集合属性(DataSet.Tables、DataTable.Rows、...).

For example, enumerating properties will generally not be thread-safe - so you would need to hold a lock for as long as any caller is enumerating any of the many collection properties (DataSet.Tables, DataTable.Rows, ...).