簡體   English   中英

使用多線程vb.net時更新文本框

[英]update textbox when using multi thread vb.net

我的密碼

Imports System.IO
Public Class Form1
Dim thread As System.Threading.Thread
Dim thread2 As System.Threading.Thread
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    thread = New System.Threading.Thread(AddressOf getproxy)
    thread.Start()
End Sub
Private Sub getproxy()
    Try
        Dim ip As String = "76.125.85.66:16805 | 0.238 | Little Rock | AR | Unknown | United States69.207.212.76:49233 | 0.274 | Sayre | PA | 18840 | United States96.42.127.190:25480 | 0.292 | Sartell | MN | 56377 | United States"
        For Each m As Match In Regex.Matches(ip, "(?:\d{1,3}\.){3}\d{1,3}:\d+")
            TextBox1.Text += (m.Value) & vbNewLine
        Next
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

我希望它顯示文本框所有代理格式

76.125.85.66:16805
69.207.212.76:49233
96.42.127.190:25480

但它錯誤

{“跨線程操作無效:從不是在其上創建線程的線程訪問的控件'TextBox1'。”}

一旦啟動線程,就無法從UI線程訪問控件。 您可以調用 UI線程並更新文本框。

Private Sub getproxy()
    Dim ip As String = "76.125.85.66:16805 | 0.238 | Little Rock | AR | Unknown | United States69.207.212.76:49233 | 0.274 | Sayre | PA | 18840 | United States96.42.127.190:25480 | 0.292 | Sartell | MN | 56377 | United States"
    Me.Invoke(Sub() 
     For Each m As Match In Regex.Matches(ip, "(?:\d{1,3}\.){3}\d{1,3}:\d+")         
      TextBox1.Text += (m.Value) & Enviroment.NewLine
     Next
               End Sub)
End Sub 

PS為什么您需要一個線程進行這項工作? 似乎這樣只需很少的時間即可執行。 線程處理是長時間的工作。

getproxy()內部實際上還有更多工作要做嗎?

無論如何,您僅應Invoke()實際更新UI的代碼。 其余代碼應在另一個線程中運行:

Private Sub getproxy()
    Try
        Dim ip As String = "76.125.85.66:16805 | 0.238 | Little Rock | AR | Unknown | United States69.207.212.76:49233 | 0.274 | Sayre | PA | 18840 | United States96.42.127.190:25480 | 0.292 | Sartell | MN | 56377 | United States"
        For Each m As Match In Regex.Matches(ip, "(?:\d{1,3}\.){3}\d{1,3}:\d+")

            ' ... possibly some other work done with "m.Value" ...

            ' Invoke just the updating of the UI itself:
            TextBox1.Invoke(Sub()
                                TextBox1.AppendText(m.Value & vbNewLine)
                            End Sub)
        Next
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM