2014-09-05 171 views
0

基本上,我擁有的是一個後臺工作者。一個按鈕被點擊和按鈕有BackgroundWorker.DoWork的DoWork的溫控功能具有此代碼:For Loop Inside BackgroundWorker.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.

可有人請這個問題幫助我。我只是不知道爲什麼它不會工作。

回答

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 
    ' ... 

欲瞭解更多信息,請參閱:BackgroundWorker.RunWorkerAsync Method (Object)