0

我需要運行一個報告,獲取學生測試的摘要,其中顯示通過或失敗的細節。當點擊cmd_Start時,它會在每個學生的Backgroundworker上運行(我只是想以多線程的形式運行,並且我發現有人建議使用backgroundworker),並在完成所有計算後彈出一個帶有結果的消息框。我在其他例子上覆制和編輯了一些代碼,但我不知道應該在代碼上標記問號。其他的想法也是受歡迎的。VB.net Backgroundworker傳遞參數和返回值

Dim Passed as int32= 0 
    Dim Failed as int32 = 0 
    Dim Total as int32 = 0 

    Private Sub cmd_Start_Click(sender As Object, e As EventArgs) Handles cmd_Start.Click 
    Passed= 0 
    Failed = 0 
    Total = 0 
    For i as int32 = 0 to ubound(StudentIDAry) 
     Dim worker As New System.ComponentModel.BackgroundWorker 
     AddHandler worker.DoWork, ????? CountAverageScore(????,????, StudentIDAry(i)) 
     AddHandler worker.RunWorkerCompleted, AddressOf HandleThreadCompletion 
     worker.RunWorkerAsync() 
    Next 
    MsgBox("Total Counted: " & Total & vbcrlf & "Passed Count: " & Passed & vbcrlf & "Failed Count: " & Failed) 
    End Sub 

    Private Sub CountAverageScore(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs, ByVal StudentID As Long) 
    Dim stroutput As String = e.Argument.ToString 
    .......... 
    .......... 
    e.Result = stroutput 
    End Sub 

    Private Sub HandleThreadCompletion(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) 
    Dim return_value As String = e.Result.ToString 
    If cint(return_value)>=50 Then 
     Passed = Passed + 1 
    Else 
     Failed = Failed + 1 
    End If 
    Total = Total + 1 
End Sub 
+0

不能隨意添加參數的事件處理程序,發件人和e BackgroundWorker的提供。既然你只有一個變量可以傳遞,你可以簡單地將它傳遞給RunWorkerAsync,並在CLng(e.Argument)的事件處理程序中再次檢索它。 –

回答

-1

而不是使用所有代碼添加您自己的後臺工作者,試試這個。它使用Parallel.For並在其自己的線程中運行循環內的所有內容。

Parallel.For的結構非常簡單,但重要的是要記住表示循環的最後一次迭代的數字是排他性的。

例如在一個規則的循環For I As Integer =0 to 100中,將會在100處,但在Parallel.For循環中,最後一次迭代將是99.令人討厭的是,但事實就是這樣。

由於多線程的性能開銷,您的代碼運行速度可能不會更快,因此與常規循環相比,檢查並行循環運行速度可能會有所值。

不要忘記改變我的代碼位,我使用StudentStruct代表你用來代表一個學生的任何對象。

Private Sub cmd_Start_Click(sender As Object, e As EventArgs) Handles cmd_Start.Click 
    Passed = 0 
    Failed = 0 
    Total = 0 
      Parallel.For(0, UBound(StudentIDAry) + 1, 
             Sub(index As Integer) 
              Dim studentAverage As Integer = CInt(CountAverageScore(StudentIDAry(index))) 
              If CInt(studentAverage) >= 50 Then 
               Passed = Passed + 1 
              Else 
               Failed = Failed + 1 
              End If 
              Total = Total + 1 
             End Sub) 
    MsgBox("Total Counted: " & Total & vbCrLf & "Passed Count: " & Passed & vbCrLf & "Failed Count: " & Failed) 
End Sub 


Private Function CountAverageScore(student As StudentStruct) As Single 
    Dim score As Integer 
    ' 
    ' 
    ' 
    Return score 
End Function 

溝所有BackgroundWorker的代碼,只需使用上述