Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

multithreading - Threading & Cross Threading in C#.NET, How do I change ComboBox Data from another Thread?

I need to use threading in my app, but I don't know how to perform a cross threading operation.

I want to be able to change the text of a form object (in this case a Combo Box), from another thread, I get the error:

Cross-thread operation not valid: Control 'titlescomboBox' accessed from a thread other than the thread it was created on.

I don't really understand how to use the invoke and begin invoke functions, So im really looking for a dead simple example and explanation for this so I can learn around that.

Also any beginner tutorials would be great, I found a few, but their all so different, I don't understand exactly what I need to do to perform cross threading ops.

Here is the code:

    // Main Thread. On click of the refresh button
    private void refreshButton_Click(object sender, EventArgs e)
    {
        titlescomboBox.Items.Clear();
        Thread t1 = new Thread(updateCombo);
        t1.Start();
    }

    // This function updates the combo box with the rssData
    private void updateCombo()
    {
        rssData = getRssData(channelTextBox.Text);       // Getting the Data
        for (int i = 0; i < rssData.GetLength(0); i++)   // Output it
        {

            if (rssData[i, 0] != null)
            {

              // Cross-thread operation not valid: Control 'titlescomboBox' 
              // accessed from a thread other than the thread it was created on.

              titlescomboBox.Items.Add(rssData[i, 0]);   // Here I get an Error

            }
            titlescomboBox.SelectedIndex = 0;
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I use the following helper class:

public static class ControlExtensions
{
    public static void Invoke(this Control control, Action action)
    {
        if (control.InvokeRequired)
        {
            control.Invoke(new MethodInvoker(action), null);
        }
        else
        {
            action.Invoke();
        }
    }
}

Now you can call something like MyCombo.Invoke(() => { MyCombo.Items.Add(something); }) --- or any other control (such as the form) before the invoke since they are all created on the main thread.

The thing is that controls can only be accessed from the thread they were created on (the main application thread in this case).

HTH


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...