vb.net - 如何在 WPF VB.net 中对 Windows 窗体控件进行线程安全调用
问题描述
我正在尝试对 WPF VB.net 中的表单控件进行安全调用,但我无法做到。通常我是通过委托完成的,但显然在 WPF 中它是不同的。有任何想法吗??问候。
Delegate Sub SetTextCallback(ByVal text As String)
Private Sub SetText(ByVal text As String)
If lProcess.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetText)
Me.Invoke(d, New Object() {text})
Else
Me.lProcess.Text = text
End If
Application.DoEvents()
End Sub
解决方案
您不需要声明自己的委托。只需使用适当的Action
or Func
。您也不需要为Invoke
接受 a的参数显式创建一个数组ParamArray
。
Private Sub SetText(ByVal text As String)
If Me.Dispatcher.CheckAccess() Then
'We are on the UI thread.
Me.lProcess.Text = text
Else
'We are on a secondary thread.
Dim d As New Action(Of String)(AddressOf SetText)
Me.Dispatcher.Invoke(d, text)
End If
End Sub
这是未经测试的,但我认为它应该可以完成这项工作。我从未在 WPF 中使用过 WinForms 控件,因此实际设置的行Text
可能无效,但我假设您已经知道如何执行该部分。
基本上,除了结果相反之外,Dispatcher.Invoke
几乎与 相同Control.Invoke
并且Dispatcher.CheckAccess
等效。Control.InvokeRequired
推荐阅读
- python - 如何通过从文本文件中获取 rssi 值来计算距离?
- c++ - 在 C++ 中将强类型枚举转换为 int 的替代方法
- html - 为什么只有 2 个 last-of-type CSS 工作中的 1 个
- c++ - 如何仅在页面文件中强制分配?
- python - 如何提高默克尔根计算的速度?
- c - 将链表中的节点移动到前面,以便将其移动到不同的链表
- c# - 无法将字符串数组的类型“int”隐式转换为“string”
- crystal-reports - Crystal Reports - 在公式中插入 SQL 查询
- azure-devops-pipelines - 将 PR 构建限制为特定路径
- javascript - Keyup 有效,而 keypress 无效 Vanilla JS