gpt4 book ai didi

vb.net - 表单控件数组上的线程安全调用

转载 作者:行者123 更新时间:2023-12-04 05:44:27 24 4
gpt4 key购买 nike

我正在尝试从单独的线程访问动态生成的控件。
但是我的代码总是出现“堆​​栈溢出异常”。

我正在使用以下代码:

Private _workerThread As Threading.Thread

Private Sub Main_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim Label As New Label
Label.Name = "Label1"
Label.Location = New System.Drawing.Point(12, 12)
Label.Text = String.Empty
Label.AutoSize = True

Controls.Add(Label)

_workerThread = New Threading.Thread(AddressOf DoWork)
_workerThread.Priority = Threading.ThreadPriority.BelowNormal
_workerThread.Start()
End Sub

Private Sub DoWork()
SetLabelText("Label1", "text")
End Sub

Delegate Sub SetLabelTextCallback(ByVal LabelName As String, ByVal text As String)
Private Sub SetLabelText(ByVal LabelName As String, ByVal text As String)
If CType(Me.Controls(LabelName), Label).InvokeRequired Then
Dim d As New SetLabelTextCallback(AddressOf SetLabelText)
d.Invoke(LabelName, text)
Else
CType(Me.Controls(LabelName), Label).Text = text
End If
End Sub

显然 InvokeRequired 永远不会变为 False。但我不明白为什么。
也许有人可以告诉我我做错了什么。

最佳答案

您没有在标签的线程上调用方法 SetLabelTextCallback,
因此你会在同一个线程上再次记忆,并且 InvokeRequired 永远不会是假的

Delegate Sub SetLabelTextCallback(ByVal LabelName As String, ByVal text As String) 

Private Sub SetLabelText(ByVal LabelName As String, ByVal text As String)
Dim l as Label = CType(Me.Controls(LabelName), Label)
if l.InvokeRequired then
Dim d As New SetLabelTextCallback(AddressOf SetLabelText)
l.Invoke(d, new Object() {LabelName, text} )
Else
l.Text = text
End If
End Sub

关于vb.net - 表单控件数组上的线程安全调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10865408/

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