数据表并发锁定
我正在帮助完善一个应用程序,它充满了并发问题。我正在尝试解决它们,并遇到了使用数据表的部分。
数据表本身是静态的,在多个线程之间共享。
我知道使用 dt.Select("...") 本身需要一个锁定语句,否则在向数据表添加/删除行时会遇到问题。但是,当该调用返回时,您将拥有一个 DataRow 对象数组。
如果我要更新它们,我显然会锁定这些行,但如果我只是读取它们,它们是否需要锁定?
基本上,考虑到我们在其他地方添加新行并可能更新现有行,以下哪一个是正确的:
lock (dtLock)
{
DataRow[] rows = dt.Select("...");
}
foreach(DataRow dr in rows)
{
// read statements only
}
或
lock (dtLock)
{
DataRow[] rows = dt.Select("...");
foreach(DataRow dr in rows)
{
// read statements only
}
}
I'm helping spruce up an application, and it's full of concurrency issues. I'm attempting to work through them, and came across a section that's using DataTables.
The datatable itself is static, shared across many threads.
I know that using dt.Select("...") itself needs a lock statement, or you'll have issues when adding/removing rows to the data table. However, when that call returns, you have an array of DataRow objects.
I'd obviously lock those rows if I was to update them, but if I'm just reading them, do they need locking?
Basically, given that elsewhere we're adding new rows and potentially updating existing rows, which of these is correct:
lock (dtLock)
{
DataRow[] rows = dt.Select("...");
}
foreach(DataRow dr in rows)
{
// read statements only
}
or
lock (dtLock)
{
DataRow[] rows = dt.Select("...");
foreach(DataRow dr in rows)
{
// read statements only
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您声明将更新现有行,因此您别无选择,只能锁定对从
Select
中提取的行的访问。如果其他线程可能修改这些行,则您不能(或至少不应该)访问这些行,即使只是读取。此外,访问单个行可能会影响底层 DataTable 的内部结构(我自己也看到过证据),因此即使您只是添加新行,仍然可能 /em> 是个问题。Since you stated that you will be updating existing rows then you have no other choice but to lock access to the rows you extract from
Select
. You cannot (or at least should not) access the rows, even just reads, if there is a possibility that they can be modified by another thread. Furthermore it is possible (and I have seen ancedotal evidence myself) that accessing an individual row can touch the underlyingDataTable
's internal structure so even if you were just adding new rows there still might be a problem.