在写VB.net时,遇到要在线程里改变Form上的ListView控件中的信息,动手做起来才发现并不是那么容易。因为微软的框架并不鼓励在线程里直接访问Form上的控件。因为这样会改变UI进程的正常执行。如果必须这样做,需要在线程中使用Invoke函数或者InvokeBegin函数。下面是一个例子:
Imports System.Threading
Public Class Form1
Delegate Sub AddListItem(ByVal IPString As String, ByVal ScanPort As Integer)
Public myDelegate As AddListItem
Public OpenPortCount As Integer = 0
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myDelegate = New AddListItem(AddressOf AddListItemMethod)
End Sub
Private Sub Start_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Start_Button.Click
Dim mythread As Thread
mythread = New Thread(New ThreadStart(AddressOf ThreadFunction))
mythread.Start()
End Sub
Private Sub ThreadFunction()
Dim mythread As Thread
mythread = New Thread(New ThreadStart(AddressOf DoScanThread))
mythread.Start()
End Sub 'ThreadFunction
Private Sub DoScanThread()
Dim myThreadClassObject As New ScanThreadClass(Me)
myThreadClassObject.run()
End Sub
Public Sub AddListItemMethod(ByVal IPString As String, ByVal scanport As Integer)
ListView_Result.Items.Add(IPString, OpenPortCount) 'ScanIP.ToString(), 0)
ListView_Result.Items(OpenPortCount).SubItems.Add(scanport.ToString())
OpenPortCount += 1
End Sub 'AddListItemMethod
End Class
Public Class ScanThreadClass
Private myFormControl1 As Form1
Public Sub New(ByVal myForm As Form1)
myFormControl1 = myForm
End Sub 'New
Public Sub run()
myFormControl1.Invoke(myFormControl1.myDelegate, New Object() {"11", 123})
End Sub
End Class
主要注意的就是Invoke的调用和Delegate的定义。