在后台工作时与表单交互

时间:2017-02-13 17:11:30

标签: vb.net

目标是在代码运行时表单仍然可以被点击(主要是为了能够破解代码)并且同时继续通过运行代码进行更新。第一部分是有效的,而不是第二部分。

Public Class FormMain
    Public PleaseStopAll As Boolean
    Private Sub BreakCode_Click(sender As Object, e As EventArgs) Handles BreakCode.Click
        PleaseStopAll = True
    End Sub

    Private Sub Testeur_Click(sender As Object, e As EventArgs) Handles Testeur.Click
        PleaseStopAll = False
        ThreadPool.QueueUserWorkItem(AddressOf LaunchTask, 0)
    End Sub

    Sub LaunchTask(o As Object)
        TheTask(Me)
    End Sub
    Public Sub ShowSomeMessage(msg As String
             Me.Displayer.text = msg
    End Sub
End Class

Module TaskDoer
    Sub TheTask(MyMenu As FormMain)
        For i As Integer = 0 To 42
            whatever() 'some tasks that cannot be interrupted safely
            MyMenu.ShowSomeMessage("task #" & CStr(i) & " over")  ' Here is the error
            If MyMenu.PleaseStopAll Then Exit For
        Next
    End Sub
End Module

"状态更新" line告诉该任务无法与其父任务进行交互。 如果我删除这一行,代码运行就好了:代码在我要求时中断,并且表单仍然可以点击。

我尝试使用BackgroundWorker,但它需要实际的进展报告一些ReportProgress(增加%)我不能只提供一个状态(作为字符串)

1 个答案:

答案 0 :(得分:0)

通过变量或结构传递任何其他内容

 BackgroundWorker1.WorkerReportsProgress = True '<Make sure this is set
 BackgroundWorker1.RunWorkerAsync()



Private SomeStatus As String
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    SomeStatus = "Hello"
    BackgroundWorker1.ReportProgress(0)
End Sub

Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
    ShowSOmeMEssage(SomeStatus)
End Sub

仅供参考:进度只是为了你可以在主UI线程上调用例程。您可以在backgroundworker中的表单上设置任意数量的线程安全变量。它只是更新了令人讨厌的用户界面,尽管也有一种解决方法。