线程安全隐藏表单

时间:2014-07-04 14:22:58

标签: vb.net multithreading winforms thread-safety show-hide

我试图做一个"加载......"使用BackgroundWorker( netMessageInWait )在带有简单动画的DLL中形成。

我有一个显示功能,可以加载表单,设置所有文本并运行BackgroundWorker

Public Sub Show(ByVal WorkingArea As Rectangle, ByVal Title As String, ByVal Message As String)
     With wait
        If (wait.InvokeRequired) Then
            wait.Invoke(Sub()
                            With .lblTitle
                                .Text = Title
                            End With
                            With .lblMessage
                                .Text = Message
                            End With
                        End Sub)
        Else
            With .lblTitle
                .Text = Title
            End With
            With .lblMessage
                .Text = Message
            End With
        End If
    End With

    If (Not backWorker.IsBusy) Then
        Dim args As New ShowArgumentType
        args.WorkingArea = WorkingArea
        args.Title = Title
        args.Message = Message

        backWorker.WorkerSupportsCancellation = True
        backWorker.RunWorkerAsync(args)
    End If    
End Sub

停止BackgroundWorker的清除功能

Public Sub ClearMessage()
    Try
        CancelWork = True
        backWorker.CancelAsync()

    Catch ex As Exception
        Debug.Print(ex.Message)
    End Try
End Sub

BackgroundWorker_DoWork(),显示表格并等待 ClearMessage

Private Sub backWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles backWorker.DoWork
    Dim args As ShowArgumentType = DirectCast(e.Argument, ShowArgumentType)

    wait.Show()

    While True
        Application.DoEvents()
        If (CancelWork Or backWorker.CancellationPending) Then
            Exit While
        End If
    End While

End Sub

然后隐藏表单的 BackgroundWorker_RunWorkerCompleted()

Private Sub backWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles backWorker.RunWorkerCompleted
    CancelWork = False

    Call ShowHideForm_ThreadSafe(wait, False) ' HERE THE PROBLEM

    Debug.Print("Work completed")
End Sub

好的...我不明白为什么我试图在BeginInvoke的程序freez下面隐藏表单函数...

Private Sub ShowHideForm_ThreadSafe(ByVal pform As Form, _
                                    ByVal pshow As Boolean)
    If pform.InvokeRequired Then
        Dim MyDelegate As New ShowHideForm_Delegate(AddressOf ShowHideForm_ThreadSafe)



        pform.BeginInvoke(MyDelegate, New Object() {[pform], [pshow]})


    Else
        If (pshow) Then
            pform.Show()
        Else
            pform.Hide()
        End If
    End If

End Sub

请帮帮我!我该如何解决这个问题? 谢谢!

0 个答案:

没有答案