线程问题(我不明白)

时间:2015-06-12 15:02:57

标签: vb.net multithreading class listbox invoke

互联网上有很多关于穿线的网页,但我似乎无法理解它。

我有一个表单,只需单击一个按钮,就可以循环浏览文件并逐行读取。每行是不同FTP站点的登录详细信息。

当它读取一行时,它使用登录详细信息将一个变量变为一个名为CallFTP的类的新实例。

然后使用CallFTP中名为PerformFTP的函数将变量作为新线程变暗。

PerformFTP返回一个包含FTP结果的字符串,我想将其添加到开始表单的表单上的ListBox中。

按钮的代码是这样的......

Private Sub cmdRun_Click(sender As Object, e As EventArgs) Handles cmdRun.Click
    For Each _FTPLine As String In Split(_FTPDetails, vbNewLine)
        Dim _Active As Boolean = CBool(Split(_FTPLine, "|")(7))

        If _Active Then
            _CurNum += 1
            _ID = Format(Now.Year, "0000") & Format(Now.Month, "00") & Format(Now.Day, "00") & Format(Now.Hour, "00") & Format(Now.Minute, "00") & Format(Now.Second, "00") & Format(Now.Millisecond, "000") & Format(_CurNum, "00000")

            Dim _FTP As New CallFTP(_ID, Split(_FTPLine, "|")(0), Split(_FTPLine, "|")(1), Split(_FTPLine, "|")(2), Split(_FTPLine, "|")(3), Split(_FTPLine, "|")(4), Split(_FTPLine, "|")(5), Split(_FTPLine, "|")(6))
            Dim _Thread = New Thread(New ThreadStart(AddressOf _FTP.PerformFTP))

            With _Thread
                .IsBackground = True
                .Start()
            End With
        End If
    Next _FTPLine
End Sub

该类如下(不完全但你不需要其余的代码lol)

Public Class CallFTP
    Private _ID As String = ""
    Private _Response As String = ""
    Private _IPAddress As String = ""
    Private _Port As String = ""
    Private _User As String = ""
    Private _Pass As String = ""
    Private _Remote As String = ""
    Private _Local As String = ""
    Private _InOut As String = ""

    Public Sub New(ID As String, Server As String, PortNum As String, Username As String, Password As String, RemoteDir As String, LocalDir As String, InOrOut As String)
        _ID = ID
        _IPAddress = Server
        _Port = PortNum
        _User = Username
        _Pass = Password
        _Remote = RemoteDir
        _Local = LocalDir
        _InOut = InOrOut
    End Sub

    Public Function PerformFTP() As String
        Return "This is a test"
    End Function
End Class

有人可以解释我如何在名为modMisc的模块上调用一个名为LogMessage的子命令(它将一个字符串添加到主窗体上的ListBox中)?

我读过你需要调用它,但我读到的所有东西似乎让我头疼,让我需要躺在黑暗的房间里几个小时。

是否有人能够解释,就好像你正在和一个2岁的孩子说话一样? :)

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

如果要从创建它的另一个线程更新GUI,则需要调用委托来更新GUI。

1º您的代表必须与您使用的方法相匹配(具有相同的签名):

    Delegate Sub LogMessageExampleDelegate(ByVal x As Integer, ...)

签名意味着委托必须返回并接收与您的函数/方法相同的类型。

2º调用您的函数以使用委托更新GUI。例如,在更新GUI功能中:

If yourListBox.InvokeRequired Then
    yourListBox.Invoke(New LogMessageExampleDelegate(AddressOf THE_FUNCTION_WHICH_UPDATES_THE_GUI_NAME), parameter_value)
Else
    'Just call your function
End If

以:例如:

sub addToListBox(byval text as string)
    myListBox.Items.add(text)
end sub

所以你的调用将是:

If yourListBox.InvokeRequired Then
    yourListBox.Invoke(New LogMessageExampleDelegate(AddressOf addToListBox), "Item 1")
Else
    'Just call your function
    addToListBox("Item 1")
End If
PS:我写了两次,所以希望我没有注意到它没有注意到它。