A day with .Net

My day to day experince in .net

Cross-thread operation not valid task parallel library

Posted by vivekcek on May 31, 2012

I have 2 drop down list in a windows form application. On the selected index change event of first i want to add an item to second drop down. I just used Task Parallel Library and wrote the below code. It give me an error like “Cross-thread operation not valid: Control ‘ddlRqType’ accessed from a thread other than the thread it was created on.”

My Initial Code

 private void ddlCMType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlCMType.SelectedItem.ToString() == "Portal")
            {
                Task.Factory.StartNew(() =>

                    {
                        ddlRqType.Items.Add("hai");
                    }
                    );
            }
        }


Then i corrected it using Invoke and delegate

  private void ddlCMType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlCMType.SelectedItem.ToString() == "Portal")
            {
                Task.Factory.StartNew(() =>

                    {
                        this.Invoke(new MethodInvoker(delegate { ddlRqType.Items.Add("hai"); }));
                    }
                    );
            }
        }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s