locked
Background Worker "Cross-thread operation not valid; Control *controlhere* accessed from thread other than the thread it was created" RRS feed

  • Question

  • I have a combobox with a list of crewmembers on a forum. The user selects a crewmember, an SQL query fires and obtains the credentials for the corresponding crewmember, and displays them in a textbox. This process can take a few second. I'm using the backgroundWorker to keep the UI from locking up while this takes place. Below is the code:

            
    //Combobox Selection Event
    private void cboTertiary_SelectionIndexChanged(object   sender, EventArgs e)
            {
                string crewMember = cboTertiary.Text;
                backgroundWorker1.RunWorkerAsync(crewMember);
            }
    
    //Background Worker DoWork Event
    
            private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
            {
                {
                    try
                    {
    
                       
                        string crewMember = (string)e.Argument.ToString();
                        
                        OleDbConnection connection = new OleDbConnection();
                        connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source = S:\Databases\TestApplications\backend\FollowUpApp_BE.accdb;
                                                    Persist Security Info=False";
    
                        connection.Open();
    
                        OleDbCommand getCredentials = new OleDbCommand();
                        getCredentials.Connection = connection;
                        string query = "select Credentials FROM tblCrewmembers WHERE Crewmember='" + cboTertiary.Text + "'";
                        getCredentials.CommandText = query;
    
                        OleDbDataReader reader = getCredentials.ExecuteReader();
    
                        while (reader.Read())
                        {
    
                            string credential = reader["Credentials"].ToString();
                            
                            e.Result = credential.ToString();
    
                        }
    
                        reader.Close();
                        connection.Close();
                    }
                    catch (System.Reflection.TargetInvocationException ex)
                    {
                        MessageBox.Show("Error: " + ex);
                    }
                }
            }
    
    //Backgroundworker RunWorkerCompleted Event
    
            private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
            {
                try
                {
    
                    //******ERROR OCCURS HERE******
                    txtTertiaryCred.Text = e.Result.ToString();
                }
                catch (System.Reflection.TargetInvocationException ex)
                {
                    MessageBox.Show("Error: " + ex);
                }
            }
    I've searched for a solution for hours and haven't found one.


    Saturday, August 20, 2016 12:33 AM

Answers

  • Multithreading and GUI's do not mix. Wich is why all GUI classes were equipped to actively check if you try to write them from another thread and just not allow it.
    With manual threading you have to invoke the code to do it properly.

    With BackgroundWorker, the ReportProgress and RunWorkerCompleted are automatically invoked and as such the primary place to do GUI updates.
    Something is really wierd if you got a Cross Thread Exception in the RunWorkerCompleted event.
    Could it be you are creating the BackgroundWorker from another thread? Or maybe the GUI elements were not created by the GUI/Main thread?
    BGW will just invoke on it's owner thread wich is assumed to be the GUI thread, the same all GUI elements were created on. If that does not apply, something is really wierd with your design overall and needs to be reviewed.

    You should propably get rid of those Try/catch blocks. What you have here is a boneheaded exception, and those you should never catch:
    Vexing exceptions - Fabulous Adventures In Coding - Site Home - MSDN Blogs
    Saturday, August 20, 2016 8:37 AM