Search code examples
textcomboboxtextboxbackgroundworker

Read textBox.Text in BackGroundWorker


I am using background worker to do a long process on some files. I take the address of a directory from textBox1 and the address of a file that is used for the processing function from textBox2. I also have a ComboBox. Based on the selected value of the ComboBox the program chooses a different function through a simple switch case.

Now the problem is that I can not access the values of these textBoxes and the ComboBox in the BackGroundWorker_DoWork. I of course get the exception of accessing a control from a thread it wasn't created on. I have searched a lot about delegates and all that. The examples I have seen so far are all about assigning a text to the textBox inside the program. While what I want to do is to read the text that the user has inserted into the textBox. Since I'm not quite familiar with the concept of delegates, I want to know how I can read and use the Texts of textBoxes and the ComboBox and process them in the BackGroundWorker?

Sorry I cannot post the code here due to security policies.

/MoNoo


Solution

  • You don't say if this is WinForms, WPF or Silverlight, but in WPF you would do this using the Dispatcher property of the combobox, something like this:

        string theText;
    
        myComboBox.Dispatcher.Invoke( DispatcherPriority.Normal,
                new Action( delegate()
                {
                    theText = myComboBox.Text;
                }
            ));
    

    That will marshal the call onto the main thread and back again.