Click here to Skip to main content
16,020,377 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hei,
i am doing project in that i got one error
Cross-thread operation not valid: Control 'lblEmergencyStopIndicator' accessed from a thread other than the thread it was created on.
Posted
Updated 16-Jan-12 20:35pm
v2

You can only access User Interface (or UI) components from the thread they were created on: the UI thread. If you try to access them from a different thread, you will get this error.

The solution is to Invoke the control instead.
Fore exampole, suppose you want to add a new Tab to a Tabpage from a background thread. All you have to do is check, and invoke as necessary:

C#
private void AddNewTab(string tabName)
    {
    if (InvokeRequired)
        {
        Invoke(new MethodInvoker(delegate { AddNewTab(tabName); }));
        }
    else
        {
        TabPage tp = new TabPage(tabName);
        myTabControl.TabPages.Add(tp);
        }
    }
 
Share this answer
 
You cannot call anything related to UI from non-UI thread. Instead, you need to use the method Invoke or BeginInvoke of System.Windows.Threading.Dispatcher (for both Forms or WPF) or System.Windows.Forms.Control (Forms only).

You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].

See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[^],
Control events not firing after enable disable + multithreading[^].

—SA
 
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