我正在研究一个多线程应用程序,并遇到了在线程之间传递参数的问题。
Private Students as Students
Private ListOfStudents as List(Of Students.Student)
Public Sub AddStudents()
Dim AddThread As New Thread(AddressOf Add)
AddThread.SetApartmentState(ApartmentState.STA)
AddThread.Start(Param)
End Sub
Private Sub Add(Byval Param as String)
Students = new Students(Param) 'Add Students to List
ListOfStudents = Students.GetStudents() 'Returns List of Students
For Each S in ListOfStudents
Dim L As New ListViewItem(S.Name)
L.SubItems.Add(S.Marks)
ListView1.Items.Add(L)
Next
End Sub
这很好用。 现在..
Public Sub GetStudentInfo()
For Each S in ListOfStudents
Dim SubThread As New Thread(AddressOf CheckStudent)
SubThread.SetApartmentState(ApartmentState.STA)
SubThread.IsBackground = True
SubThread.Start(S)
Next
End Sub
Private Result as String
Private Sub CheckStudent(Byval S as Students.Student)
Result &= S.Name & ":" & S.Marks
End Sub
结果应该是Ravi:92但它总是没有。 结果为null:null / Nothing:Nothing
以下是学生班:
Public Class Students
Public Class Student
Public Property Name As String
Public Property Marks As String
End Class
Public Function GetStudents() As List(Of Student)
Dim N as New List(Of Student)
N = ''code
Return N
End Function
End Class
我做了一些研究,可能会发生这种情况,因为列表是在一个单独的线程上修改的(AddThread),而另一个线程正在调用它来检索列表(SubThread)。 我该怎么办?