1

I am trying to loop through a listbox which contains filenames and upload them to an FTP server with a background worker. I am getting a cross-thread exception at my for loop when I attempt to access Listbox1.Items.Count within background worker (obviously because it's on a different thread) so I'm curious how I can pass the listbox into my background worker to execute the code they way I have written it below?

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
4

3 回答 3

0

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

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

Dim ddl = CType(e.Arugment, DropDownList)

BackgroundWorker.RunWorkerAsync 方法

于 2012-12-07T09:12:12.383 回答
0

将项目作为字符串数组传递给后台工作人员:

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

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

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
于 2012-12-07T09:12:41.633 回答
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;
        }));
于 2012-12-07T11:30:58.217 回答