【问题标题】:IndexOutOfRangeException on Datatable数据表上的 IndexOutOfRangeException
【发布时间】:2026-01-16 04:05:02
【问题描述】:

我有一个应用程序,其中 DAQ 系统以大约 1 kHz 的频率对数据进行采样,然后将其写入 DataTable。

下面的代码块显示了将数据添加到数据表的部分代码。

    Public Sub AddTimeLoadData(DateTime As DateTime, DataPointNo As Integer, ClampForceN As Double, _
                               TransverseForceN As Double, TransverseDispMm As Double, NumLoadCycles As Integer)

        Try
            _tblTimeLoadData.AddtblTimeLoadDataRow(NumLoadCycles, TransverseDispMm, TransverseForceN, ClampForceN, DataPointNo, DateTime, _TimeLoadTestRow)
            _timRaiseDataAdded.Start()
        Catch ex As Exception
            Throw New Exception("Time/load data could not be added: " & ex.Message, ex)
        End Try
    End Sub

每次调用 AddTimeLoadData 时都不需要更新 GUI,因此我启动了 System.Timers.Timer。在计时器的 Elapsed 事件中,我引发 TimeLoadDataUpdated 事件。

在 GUI 中,另一个类正在侦听此事件,并更新图表。这在大多数情况下都很好用,但有时我在从数据表中读取时会收到 IndexOutOfRangeException。

很明显,这与同步有关,但我还没有弄清楚到底是什么问题。 查看代码,索引“i”实际上不会超出范围。 出现的一个想法是,如果 for 循环在创建它的同时到达最后一行,我可能会遇到问题,所以我可以尝试将 for 循环更新为

For i As Integer = s.Points.Count To sender.tblTimeLoadData.Count - 2

或者我已经预见到了别的什么!?

【问题讨论】:

  • 好吧 - 看到您已查明错误并处于调试模式; s.Points.Countsender.tblTimeLoadData.Count 的值是多少,并与行数进行比较?
  • 很奇怪,当我检查调试器时,'I' 永远不会大于 sender.tblTimeLoadData.Count - 1。

标签: vb.net datatable indexoutofrangeexception


【解决方案1】:

VB 将 for 循环的“To”部分保存在内存中。

    Dim c As Integer

    c = 3

    ' This will print 0, 1, 2, 3
    For i As Integer = 0 To c
        c = 10
        Console.WriteLine(i)
    Next

您可能需要考虑使用 while 循环。

    Dim c As Integer

    c = 3

    Dim i As Integer = 0

    ' Will print 0 to 9
    While i < c
        c = 10
        Console.WriteLine(i)

        i += 1
    End While

或者正确同步所有内容,因为即使在 While/For 行和 Rows(i) 行之间,也有可能删除该项目。

此外,如果您的计时器用于更新 UI。您应该考虑从中删除所有业务规则。在 UI 上执行任何操作之前,让您的 ds 已经填充了正确的数据点。

【讨论】:

  • 行永远不会从 DataTable 中删除,因此 FOR 循环不应该是一个问题。我想在从 DAQ 系统接收数据时“实时”更新 UI。计时器事件处理程序中的唯一功能是将数据从数据表复制到 OxyPlot 图表系列。
  • @LinusN tblTimeLoadData 显然比开始循环时的行数更少。删除了一些行。除非您的 .Count 与您的 .Rows.Count 有所不同
  • 行不会被删除。这让我很困惑。