在寫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的定義。