基本上,我所拥有的是一名背景工作者。单击一个按钮,该按钮具有BackgroundWorker.DoWork DoWork功能具有以下代码:
For Each item In lst_Folders.CheckedItems
Dim path As String = My.Settings.stng_sourceDirectory + "\" + item.Text
For Each dirPath As String In Directory.GetDirectories(path, "*", SearchOption.AllDirectories)
Directory.CreateDirectory(dirPath.Replace(path, My.Settings.stng_saveDirectory + "\" + item.Text))
Next
'Copy all the files & Replaces any files with the same name
For Each newPath As String In Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)
File.Copy(newPath, newPath.Replace(path, My.Settings.stng_saveDirectory + "\" + item.Text), True)
Next
Next
它基本上是复制和粘贴目录,具体取决于检查哪个ListViewItem。问题是,一旦我点击按钮,背景确实有效,但我立即收到错误
Cross-thread operation not valid: Control 'lst_Folders' accessed from a thread other than the thread it was created on.
有人可以帮我解决这个问题。我不知道为什么它不起作用。
答案 0 :(得分:2)
您应该只访问UI线程上的UI控件属性。运行后台工作程序时,可以将参数传递给它。我建议您从UI复制所需的值,并将它们作为参数传递给后台工作程序,而不是让后台工作程序直接读取UI。
例如,在事件处理程序中执行以下操作:
Private Sub startAsyncButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles startAsyncButton.Click
Dim folderNames As New List(Of String)
For Each item In lst_Folders.CheckedItems
folderNames.Add(item.Text)
Next
backgroundWork.RunWorkerAsync(folderNames)
在你的工作方法中:
' This event handler is where the time-consuming work is done.
Private Sub backgroundWorker1_DoWork(ByVal sender As System.Object, _
ByVal e As DoWorkEventArgs) Handles backgroundWorker1.DoWork
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
Dim folderNames As List(of String) = CType(e.Argument, List(Of String))
For Each folderName In folderNames
Dim path As String = My.Settings.stng_sourceDirectory + "\" + folderName
' ...