我确定这是一个简单的问题。我从串口读取了一些数据,在某些解析点,我需要更新一些statuslabel。令人惊讶的是,statuslabel是线程安全的......我不知道......
好的,但是statuslabel需要包含一些似乎不是线程安全的组合文本
statLabel1.Text =“已连接到”& cmbPort.text& “,找到并开心”
所以我尝试从任何component.text创建一个“Read Safe”函数,但是我失败了......
Private Delegate Function ControlGetTextDelegate(ByRef cmp As Control) As String
Public Function ControlGetText(ByRef cmp As Control) As String
Dim s As String = ""
' control invoked from another thread ?
If cmp.InvokeRequired Then ' YES, so call through delegate
Dim dlg As New ControlGetTextDelegate(AddressOf ControlGetText)
cmp.BeginInvoke(dlg, {cmp})
Else ' NO, so call normally
s = cmp.Text
End If
Return s
End Function
有人可以提供一些帮助吗?
答案 0 :(得分:0)
我认为您的问题是,s
时您没有向InvokeRequired = True
分配任何内容。
您可以将结果分配给s
(您需要设置Invoke
而不是BeginInvoke
),但调用事件处理程序可能会更好从而调用此。您没有发布该代码,但它基本上是相同的想法 - 在表单上测试InvokeRequired
,然后为事件处理程序本身调用BeginInvoke
。