首页 > 解决方案 > 如何在 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

标签: vb.netxaml

解决方案


您不需要声明自己的委托。只需使用适当的Actionor 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


推荐阅读