vb.net - 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
解决方案
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
推荐阅读
- python - “分离源和构建目录”是什么意思?
- python - 如果用户还没有昵称,我希望能够让机器人自动将成员用户名更新为特定昵称
- html - tailwindcss 中的导航栏转换
- python - BeautifulSoup - 从 HTML 中去除不间断的空格
- java - 如何使用我的比较器对 TreeSet 中的重复项进行排序和避免重复?
- list - 如何在方案中编写程序来查找数字列表的因子
- java - Java AffineTransform 在不同系统上的工作方式不同
- javascript - HTML嵌入链接中对应于100vh的动态iframe?
- python - 如何在python中自动化图像截图过程?
- python - python ctypes中int32_t和char数组的复杂结构