我需要运行一个报告来获取学生测试的摘要,该摘要显示已通过或未通过详细信息。单击cmd_Start时,它在Backgroundworker上运行(我只想以多线程运行,我发现人们建议使用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 :(得分:-2)
不要使用添加自己的后台工作程序的所有代码,请尝试此操作。它使用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代码,只使用上面的