Click here to Skip to main content
15,892,674 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am new to multi Threadding, From google search I got so many examples and all are explaining with console applications, but when I work with windows forms it is not accepting to assign a value to any control. it is showing error

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


Please help me. and provide any useful links (multi threading with winforms)


Thanks in advance
Posted
Comments
Sergey Alexandrovich Kryukov 24-Mar-11 3:27am    
Correct tag, please: AS.net?
--SA

 
Share this answer
 
Take a look on this example. Executing the method using Invoke and BeginInvoke with delegates's aid.

Make Thread-Safe Calls to Windows Forms Controls[^]
 
Share this answer
 
I usually do something like this in UI code:

private void MoveMyCoolButton(){<br />
 if (this.InvokeRequired){<br />
   this.Invoke(new Action(MoveMyCoolButton));<br />
 }<br />
 <...> Continue on your UI code <...><br />
}
 
Share this answer
 
Yes..you cannot update controls on non-UI thread so if you want other threads
to do something with your controls you must marshal it to UI thread...
How??
Well, each control has methods Invoke( ) and BeginInvoke( ). They accept
a delegate ( a pointer to some function) and arguments to be called on
UI-thread.

 delegate void UpdateUIDelegate(int value);

// another thread method
private void DoLongCalculation( ) {
  int progress = 0;
  while( true) {
  // blah-blah-blah
  // invoking from other thread
  m_progressBar.Invoke( new UpdateUIDelegate(UpdateUI), progress);
 }
}

private void UpdateUI(int value) {
 m_progressBar.Value = value;
}
 
Share this answer
 

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