.net編程時線上程裡使用Form上的控制項的問題

來源:互聯網
上載者:User
在寫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的定義。

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.