gpt4 book ai didi

vb.net - 遍历列表的副本,仍然得到InvalidOperationException

转载 作者:行者123 更新时间:2023-12-03 13:12:42 24 4
gpt4 key购买 nike

我有一个被频繁调用的Sub,同时,辅助线程更改了它使用的所有List中的值。显然,这将导致InvalidOperationException,因此我在.ToList循环中放入了For Each,以便它在循环遍历列表之前复制了List。那是行不通的,我得到了InvalidOperationException: "Collection was modified; enumeration operation may not execute.“(而且,我不知道为什么,但是仅当在VS之外运行应用程序时才会抛出此异常,这使得调试非常困难。请注意,该错误在VS上调试应用程序时仍然存在,仅不会引发异常)。然后我尝试显式复制List,但未成功,错误仍然存​​在。这是错误的Sub:

Private Sub MasmorraPictureBox_Paint(sender As Object, e As PaintEventArgs) Handles MasmorraPictureBox.Paint
Dim c As New Integer
Dim DGridCopy As List(Of Point) = DGrid.ToList
Dim DPointsCopy As List(Of Point) = DPoints.ToList
Dim DGridColCopy As List(Of Brush) = DGridCol.ToList
Dim DPointsTextCopy As List(Of String) = DPointsText.ToList
For Each Point As Point In DGridCopy
e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
e.Graphics.FillRectangle(DGridColCopy(c), Point.X, Point.Y, 35, 35)
c += 1
Next
c = 0
For Each Point As Point In DPointsCopy
e.Graphics.FillEllipse(Brushes.Blue, Point.X - 5, Point.Y - 5, 10, 10)
e.Graphics.DrawString(DPointsTextCopy(c), MyFont, Brushes.Black, Point.X - 5, Point.Y + 10, StrFormat)
c += 1
Next
End Sub

问题是什么?

更新:通过将副本声明为原始列表的 .ToList,已经解决了该问题。我以为不是因为仍然有一些错误,但是正如我之前说的,调试器不会抛出 InvalidOperationException(即使它们正在发生),所以我只发现错误不再存在于此Sub中。我在VS之外运行了该应用程序,以发现注释中要求哪一行在扔它。

最佳答案

您无法在同时读取列表的同时写入列表。那是一场比赛。 ToList可以视为读者,因为查看列表的任何人都是读者。

使用适当的同步(如锁)。或不变的结构。

关于vb.net - 遍历列表的副本,仍然得到InvalidOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22278985/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com