首页 > 解决方案 > EventHandler 中的全局变量

问题描述

我有个问题。正如你在下面看到的,我有一个按钮事件,在那个事件中我有 MySub 和一个附加到它的事件处理程序。在遍历 myListDataGridView.Rows 时,我试图用 ID 记录每次迭代。但我不确定,但由于处理程序启动了一个新线程(可能),我无法获得正确的 ID。例如记录第 2 行,其他参数正常,但我得到第 4 行 ID。我可以通过将 ID 作为参数发送给 MySub 并返回它来解决这个问题,但我正在尝试另一种方法。由于某些公司原因。你可以帮帮我吗 ?提前致谢。

Public Class X
   Dim myVariable As Integer = 0

   AddHandler MySub, AddressOf MySubHandler

   Private Sub OKBtn_Click(sender As Object, e As EventArgs) Handles OkBtn.Click
       For Each d As DataGridViewRow In myListDataGridView.Rows 'rowcount 750
           MySub(d.Cells("ABC").Value)
           myVariable = d.Cells("ID")
       Next
   End Sub

   Private Sub MySubHandler(Data As MySubReply)
      ........
      ........
      Log(myVariable, other parameters)
   End Sub

End Class

我尝试了这个代码块,但它锁定了 UI。您可以关注 isHandlerJobDone 变量。

Public Class X
   Dim myVariable As Integer = 0
   Dim isHandlerJobDone As Boolean

   AddHandler MySub, AddressOf MySubHandler

   Private Sub OKBtn_Click(sender As Object, e As EventArgs) Handles OkBtn.Click
       isHandlerJobDone = False
       For Each d As DataGridViewRow In myListDataGridView.Rows 'rowcount 750
           MySub(d.Cells("ABC").Value)
           myVariable = d.Cells("ID")
       While Not isHandlerJobDone
       End While
       Next
   End Sub

   Private Sub MySubHandler(Data As MySubReply)
      ........
      ........
      Log(myVariable, other parameters)
      isHandlerJobDone = True
   End Sub

End Class

标签: vb.netmultithreadingwinformsevent-handling

解决方案


MySubReply 是一个类

然后尝试这样的事情,使用Dictionary(Of MySubReply, Integer)

Public Class X

    Private ID_Lookup As New Dictionary(Of MySubReply, Integer)

    Private Sub OKBtn_Click(sender As Object, e As EventArgs) Handles OkBtn.Click
        ID_Lookup.Clear()
        For Each d As DataGridViewRow In myListDataGridView.Rows 'rowcount 750
            Dim data As MySubReply = DirectCast(d.Cells("ABC").Value, MySubReply)
            ID_Lookup.Add(data, CInt(d.Cells("ID"))) ' associate the ID with this data
            MySub(data)
        Next
    End Sub

    Private Sub MySubHandler(Data As MySubReply)
        Dim ID As Integer = ID_Lookup.Item(Data) ' retrieve the ID based on Data
        ' ... use "ID" somehow ...
        Log(myVariable, other parameters)
    End Sub

End Class

推荐阅读