如何在VB .Net 2010中将列表框传递给后台工作者

时间:2012-12-07 09:03:12

标签: vb.net

我正在尝试遍历包含文件名的列表框,并将它们上传到具有后台工作程序的FTP服务器。当我尝试在后台工作程序中访问Listbox1.Items.Count时,我在for循环中得到一个跨线程异常(显然是因为它在不同的线程上)所以我很好奇我如何将列表框传递给我的后台工作者按照我在下面编写的方式执行代码?

Private Sub bgw_upAllFiles_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgw_upAllFiles.DoWork
        Dim i
        Dim toPath As String = MyForms.MoveOutFTPFormDir & PDFVar_PHOTO_URL_NUM & "/"
        For i = 0 To e.Argument.Items.Count - 1
            Try
retryDL:

                My.Computer.Network.UploadFile(ListBox1.Items(i).ToString, toPath & IO.Path.GetFileName(ListBox1.Items(i).ToString), MyForms.MoveOutFTPUser, MyForms.MoveOutFTPPwd)
            Catch ex As Exception
                If ex.ToString.Contains("error: (550)") Then

                    'MsgBox("Need to create FTP folder")
                    Try
                        Dim myftprequest As Net.FtpWebRequest = CType(Net.FtpWebRequest.Create(toPath), System.Net.FtpWebRequest)
                        myftprequest.Credentials = New System.Net.NetworkCredential("JeffreyGinsburg", "andy86")
                        myftprequest.Method = System.Net.WebRequestMethods.Ftp.MakeDirectory
                        myftprequest.GetResponse()

                        GoTo retryDL


                    Catch ex2 As Exception
                        ex2.ToString()
                    End Try

                Else
                    MsgBox(ex.ToString)

                End If
                MDIParent1.StatusStrip.Items.Item(2).Text = "Upload Complete"
            End Try
        Next

    End Sub

3 个答案:

答案 0 :(得分:0)

当您调用RunWorkerAsync时,您可以将对象作为参数传递。你可以使用这个对象并传入你的DDL。

然后,在DoWork事件中,您可以像这样使用DDL:

Dim ddl = CType(e.Arugment, DropDownList)

BackgroundWorker.RunWorkerAsync Method

答案 1 :(得分:0)

将项目作为字符串数组传递给backgroundworker:

    BackgroundWorker1.RunWorkerAsync(ListBox1.Items.Cast(Of String).ToArray)

然后在dowork sub中迭代该数组:

Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    Dim files As String() = DirectCast(e.Argument, String())

    For Each file As String In files
        'My.Computer.Network.UploadFile(file, ......
    Next
End Sub

答案 2 :(得分:0)

你有两个选择:

在不同的线程上运行:

worker.RunWorkerAsync(Listbox1.Items.Cast()。ToList())

然后使用:

    private void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        var items = e.Argument as List<string>;
    }

或者你在主线程上调用动作:

        ListBox1.Invoke(new Action(() =>
        {
            var items = ListBox1.Items;
        }));