Click here to Skip to main content
15,902,756 members
Please Sign up or sign in to vote.
2.25/5 (4 votes)
See more:
when I am running my code following error appeard which then showed that it linked to the update of a textBox in each iteration.

C#
epoch++;
// check the conditions to stop
if ((epochs != 0) && (epoch > epochs))
    break;

// set current epoch's info
textBox.Text = epoch.ToString();


An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll

The calling thread cannot access this object because a different thread owns it.

How can I resolve it?

regards
AM
Posted

1 solution

easy, you are using more threads. But the GUI thread cannot be updated from another thread. You need some invoking:
C#
textBox.Invoke(new Action(()=> textBox.Text = epoch.ToString()));

That should do the trick!
All you GUI components need INVOKE when updating the values from a different thread.

GOOD Luck.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 15-Jul-15 11:35am    
5ed.
—SA
Herman<T>.Instance 16-Jul-15 3:44am    
thanx
ARMS_DEIR 20-Jul-15 8:07am    
How to avoid it from a combobox? I tried the same command but it didn't work:

Could you also please explain what does this THREAD do to avoid it later or inst it possible?
Herman<T>.Instance 20-Jul-15 8:13am    
Do you want to read or want to set the value of a combobox item?

Threads. that's quite a story.
When you have an application you have a gui thread which runs continuous. When you set a variable in a property of you object (like Text from a TextBox) you do that in the same thread. When you have a lot of processing to do before you can display anything you see a freezing windows from. To prevent that it is possible to have the processing work done by another thread. In that case you have no freeze. The problem however is that the result of the processing is in the other thread and has to be handed over to the GUI thread. In that case the Invoke method must be used to have the result available to display in your GUI.
ARMS_DEIR 20-Jul-15 8:35am    
I want to use the selected index of the defined combobox.

Is the number of Threads fixed or can I have as many as I want?

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900