Click here to Skip to main content
15,868,141 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I am trying to change a control's property inside an event (Control from a Form). Here's what I am trying to do:

- In a Timer's Event Handler, try to change a Label's text:
C#
private void someTimerEvent(object source, ElapsedEventArgs e)
{
    if (someflag == true)
    {
         lblsomelbl.Text = "1234";
    }
}


I get this error:
"Cross-thread operation not valid: Control 'lblsomelbl' accessed from another thread other than the thread it was created on."

This error makes sense to me, because the Form starts up, and then main thread creates a separate Timer that uses its own thread (my understanding). I wanted to ask you guys if there was a more proper/nicer way of doing something like this?

Is it bad programming practice to change Control properties in Events?

Thanks!
Posted

1 solution

C#
if (someflag == true)
{
     if (lblsomelbl.InvokeRequired)
         lblsomelbl.Invoke((MethodInvoker) delegate { lblsomelbl.Text = "1234"; });
     else
         lblsomelbl.Text = "1234";
}


Basically you have to change properties that interact with the UI on the same thread that the UI runs on. Using the Control.Invoke method will do that. Changing things on that other threads "own" is called cross-threading.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 2-Aug-13 18:57pm    
My 5, but with one note: "InvokeRequired" is often overused. There is no need to use it if this code is always executed in the non-UI thread. In other words, of the control belongs to the currently running UI, InvokeRequired will always return false for this UI thread and always false for any other thread. The property is only useful for a method which can have dual use: called from different threads, UI and non-UI.
—SA
Ron Beyer 2-Aug-13 20:20pm    
Very true, good point.
Sushil Mate 2-Aug-13 23:55pm    
My 5 for the solution + "informative" comment.
Sergey Alexandrovich Kryukov 3-Aug-13 0:31am    
Thank you, Sushil.
—SA

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