在寫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 AddListItemItem, ByVal ScanPort As Integer)
Public myDelegate As AddListItems sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private SubEvent_Button_Click(ByVal sender As System HandArgles eender e. Start_Button.Click
mythread = 新 Thread(New ThreadStart(AddressOf ThreadFunction))
mythread.Start()
End Sub
mythread.Start()
End Sub 'ThreadFunction
Private Sub DoScanThread()
Dim myThreadClassObject As New ScanThreadClass(Me)my
Dim myThreadClass對象IPString As String, ByVal scanport As Integer)
ListView_Result.Items.Add(IPString, OpenPortCount) 'ScanIP.ToString(), 0)
End Sub 'AddListItemMethod
End Class
Private myFormControl1 As Form1
Public Sub New(ByVal myForm As Form1)
my myFormControl1.Invoke(myFormControl1.myDelegate, New Object() {"11", 123})
End Sub