How to make Cross-Thread Calls to windows GUI

Aug 20 2008 3:00 AM

Hi,

I have a problem updating Windows Form components using a BackGroundWorker :

In my main code wrote :

Backgroundworker bgSearchFiles = new BackgroundWorker();
bgSearchFiles.DoWork += startSearch;
bgSearchFiles.WorkerSupportsCancellation = false;
bgSearchFiles.RunWorkerAsync();

Then I wrote the function :

private void startSearch(object sender, EventArgs e) {
   foreach(string file in Directory.GetFiles(folderBrowserDialog.SelectedPath) {
      statusBarInfo.Text = file.Name;
      statusBarProgress.Value = 10; //testing
      checkedListBox.Items.Add(file);
   }
}

Now the startSearch() method works perfect without the backgroundworker. The problem is that if there are too many files, the program appears to lock while searching and the progressbar doesn't update so i need in fact a backgroundworker? or other thread?

Now with the backgroundworker I got a problem calling the checkedListBox.Items.Add(file) method and the folderBrowserDialog.SelectedPath method. If I use a plain string for getting the files and comment the ListBoxItems... line then the backgroundworker is working fine and the statustext and progressbar are set right.

Why are they working while the methods give errors? I can update these windows components without any problem but it seems that I cant call methods?

How can I solve this? How can I communicate and call methods of components on a windows form to update the information right?

This is only a short version. My real code uses multiple subdirectories to be searched and multiple different form components that needs to be updated while the system is searching... the function works fine without a backgroundworker. The only problem is the locking of the program and the incorrect statusBarProgress that doesn't update.

Thanks,
Christophe.


Answers (1)