PLINQ 更新失败

发布于 2024-09-15 06:27:24 字数 397 浏览 2 评论 0原文

对不起我的英语。所以,这是我的问题 我正在尝试通过 PLINQ 更新 DataTable 这是我的代码

DataTable table = new DataTable();

table.Columns.Add(new DataColumn("val", typeof(decimal)));

int N = 1000000;

for (int i = 0; i < N; i++) table.Rows.Add(new object[] { i });

table.AsEnumerable().AsParallel().ForAll(row => row["val"] = 3);

,但有例外:“索引超出范围。必须为非负数且小于集合的大小。 参数名称:index”

请帮助我

sorry for my English. So, here is my question
I'm trying to update DataTable by PLINQ
Here is my code

DataTable table = new DataTable();

table.Columns.Add(new DataColumn("val", typeof(decimal)));

int N = 1000000;

for (int i = 0; i < N; i++) table.Rows.Add(new object[] { i });

table.AsEnumerable().AsParallel().ForAll(row => row["val"] = 3);

But there is exception:"Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"

Please, help me

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

残花月 2024-09-22 06:27:24

好吧,我现在可以告诉您,修改 a 的行并行的 DataTable 不符合 Kosher(来自关于 DataTable 类的 MSDN 文档):

这种类型对于多线程来说是安全的
读操作。您必须同步
任何写操作。

因此,虽然我不确定到底是什么导致了您提到的特定异常,但我知道您确实不应该尝试此操作,因为它不受支持。

Well, I can tell you right now that modifying the rows of a DataTable in parallel is not Kosher (from the MSDN documentation on the DataTable class):

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

So while I'm not sure exactly what's causing the particular exception you mention, I know that you really shouldn't be attempting this as it is unsupported.

凉月流沐 2024-09-22 06:27:24

找到解决方案:

table.AsEnumerable().AsParallel().ForAll(row => { lock(table)row["val"] = 3; });

但在那之后 - 平行就没有意义了

Found solution:

table.AsEnumerable().AsParallel().ForAll(row => { lock(table)row["val"] = 3; });

But after that - parallel makes no sense

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