Home  >  Article  >  Backend Development  >  Problems with using controls on Form in threads during .net programming

Problems with using controls on Form in threads during .net programming

巴扎黑
巴扎黑Original
2016-12-20 14:41:141281browse

When I was writing VB.net, I encountered the need to change the information in the ListView control on the Form in a thread. When I started doing it, I found that it was not that easy. Because Microsoft's framework does not encourage direct access to the controls on the Form in the thread. Because this will change the normal execution of the UI process. If you must do this, you need to use the Invoke function or InvokeBegin function in the thread. Here is an example:

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 -privFunction

Private Sub Doscanthread () Lass (Me) yMythreadClassObject.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

The main thing to pay attention to is the call of Invoke and the definition of Delegate.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn