Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#
I am trying to access a combobox created by drop down from the toolbox and then created a new Thread and trying add items in the combobox through the newly created thread and tje error arise like Cross-thread operation not valid: Control 'comboBox1' accessed from a thread other than the thread it was created on.
 
all the valuable solution will be appreciated
Posted 12-Jul-13 0:47am
Comments
ThePhantomUpvoter at 12-Jul-13 7:00am
   
Well the obvious solution is not to try and access controls from the non-UI thread. If you insist that you just have to do it, then use a Dispatcher for WPF or Control.Invoke for Winforms.
rajeeshsays at 24-Jul-13 5:30am
   
Solution 1 is good. I could run my program properly by add this line of code
rajeeshsays at 24-Jul-13 5:31am
   
Thank Mr.Kim Togo

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

You can only change UI Control elements from the same thread that created them. Usually Main Thread (UI Thread).
If it is WinForm, you have to switch from worker thread to Main Thread via Control.Invoke[^] commands.
 
You can do something like this:
Invoke(new Action(() => comboBox1.Items.Add("Hello from Thread"));
  Permalink  
Comments
rajeeshsays at 12-Jul-13 7:45am
   
private void AddValue()
{
this.Invoke(new Action(() => comboBox1.Items.Add("Hello from Thread")));
//comboBox1.Items.Add("hai");
}
 

private void Form1_Load(object sender, EventArgs e)
{
 
MessageBox.Show("Current Thread" + Thread.CurrentThread.Priority);
}
 
private void button1_Click(object sender, EventArgs e)
{
Second = new Thread(new ThreadStart(this.Invoke(new Action(() => comboBox1.Items.Add("Hello from Thread"))););
Second.Start();
 
}
rajeeshsays at 12-Jul-13 7:46am
   
this is my code
can you please tell what is wrong with it?
Kim Togo at 12-Jul-13 7:59am
   
Yes I can.
 
Change:
Second = new Thread(new ThreadStart(this.Invoke(new Action(() => comboBox1.Items.Add("Hello from Thread"))););
 
To:
Second = new Thread(() => this.Invoke(new Action(() => comboBox1.Items.Add("Hello from Thread"))));
Sushil Mate at 12-Jul-13 8:18am
   
much better than me..my +5,
 
mine deleted :)
Kim Togo at 12-Jul-13 8:23am
   
Thanks Sushil :-)
But you do not need to delete your solution if it works.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 355
1 Maciej Los 180
2 Richard MacCutchan 115
3 arvind mepani 104
4 Tino Fourie 92


Advertise | Privacy | Mobile
Web03 | 2.8.140709.1 | Last Updated 12 Jul 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid