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

后端 未结 3 614
被撕碎了的回忆
被撕碎了的回忆 2020-12-20 05:20

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 cas

3条回答
  •  攒了一身酷
    2020-12-20 05:51

    This exception is thrown because of you are trying to access to a control members that is created on another thread. When using controls you should access the control members only from the thread that the control created on.

    The control class helps you to know weather the control is no on the thread that is created on or not by providing InvokeRequeired property. so if 'control.InvokeRequeired' returns true that indicates that you are on a different thread. to help you out. Control support Invoke and BeginInvoke methods that will handle the execution of method to the control main thread. So:

    If you are using 3.5 and above, I suggest you to use the extension method that Eben Roux show in his answer.

    For 2.0:

    // This function updates the combo box with the rssData
    private void updateCombo()
    {
        MethodInvoker method = new MethodInvoker(delegate()
        {
        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;
        }
        });
    
        if (titlescomboBox.InvokeRequired)//if true then we are not on the control thread
        {
             titlescomboBox.Invoke(method);//use invoke to handle execution of this delegate in main thread
        }
        else
        {
            method();//execute the operation directly because we are on the control thread.
        }
    }
    

    if you use C# 2.0 this

提交回复
热议问题