线程安全调用多个控件vb net

时间:2014-02-04 07:47:37

标签: vb.net multithreading winforms .net-4.0 user-controls

我刚刚开始使用.net 4.0进行线程处理 似乎最好的方法是执行任务。我的问题是其中一个任务涉及使多个控件可见并重新定位它们,我无法找到任何安全线程调用多个控件。

以下是对任务的要求:

Parallel.Invoke(Sub()
                  HWSWChangeLayout()
                End Sub,
                Sub()
                  ValidsetUpdate1()
                End Sub)

这是其中一项任务:

Private Sub HWSWChangeLayout()

    If Me.InvokeRequired Then
        Me.Invoke(Sub() HWSWChangeLayout())
    Else
        HWSWChangeLayout()
    End If

    If strStatus = "WORK IN PROGRESS" strRole.Contains("$ORIGINATOR") Then
        'make relevant attributes visible
        Me.panCRBDate.Visible = True
        panCoordinator.Visible = True
        panSW.Visible = True
        panSW.Location = New Point(5, 189)
        panSW.Size = New Point(1216, 541)
        ET_ENG_DETS.Visible = True
        ET_FCP_DETS.Visible = True

        ET_FCP_DETS.Enabled = False
        ET_CFDU_ENG.Visible = True
        ET_CFDU_ENG.Enabled = False
        ET_PKG_DETS.Visible = True

        ET_DEP_DETS.Visible = True
        ET_DEP_DETS.Location = New Point(5, 736)
        DEP_ACT_DATE.Visible = False
        dtp_DEP_ACT_DATE.Visible = False
        lbl_DEP_ACT_DATE.Visible = False

        ET_COMMENTS.Location = New Point(5, 971)
        History.Visible = True
        Me.History.Location = New Point(5, 1206)
        Me.panAttachments.Location = New Point(5, 1441)
    End If

End Sub

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您需要从GUI-Thread调用控件更改。你可以使用Me.Invoke(也就是建议表单来做你的东西)声明这样做:

Imports System.Threading.Tasks
Public Class Form1
Private Sub DoThreadedStuff()
    'Your parallel work goes here

    'Then you want to update your main form
    If Me.InvokeRequired Then
        Me.Invoke(Sub() HWSWChangeLayout())
        Me.Invoke(Sub() ValidsetUpdate1())
    Else
        HWSWChangeLayout()
        ValidsetUpdate1()
    End If

End Sub
Private Sub HWSWChangeLayout()
    'Form update stuff
End Sub
Private Sub ValidsetUpdate1()
    'More Form update stuff
End Sub

Private Sub btnStartTask_Click(sender As Object, e As EventArgs) Handles btnStartTask.Click
    'Start the task in another thread
    Dim newTask As Task = Task.Factory.StartNew(Sub() DoThreadedStuff())
End Sub
End Class

所以你通过点击按钮开始你的任务(在这个例子中)。并行代码位于DoThreadedStuff子。从这个子目录开始,您现在想要根据我的理解更新您的主表单。所以你通过主窗体调用Update subs。通过这种方式,HWSWChangeLayout和ValidsetUpdate1在GUI线程中运行,而不是在您的附加线程中运行。