数据表并发锁定

发布于 2024-09-26 09:08:58 字数 583 浏览 6 评论 0原文

我正在帮助完善一个应用程序,它充满了并发问题。我正在尝试解决它们,并遇到了使用数据表的部分。

数据表本身是静态的,在多个线程之间共享。

我知道使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南笙 2024-10-03 09:08:58

由于您声明将更新现有行,因此您别无选择,只能锁定对从 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 underlying DataTable's internal structure so even if you were just adding new rows there still might be a problem.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文