Cross-thread operation not valid: Control ‘Form1’ accessed from a thread other than the thread it was created on

Also Check Out: My latest venture. http://loqly.me – a way for you to ask questions and get answers about local businesses around you. iTunes link: http://bit.ly/e5u4jv (only available in US for now)

The Problem :

  1. You are writing a windows application
  2. You make an asynchronous webservice call (or you launch a background worker thread to get some data)
  3. m_WebService1.FuncAsync() ‘If you are using VB.Net you probably have a member variable declared for the webservice and you are calling the MethodXXXAsync() function generated by Visual Studio when you added the WebReference.
  4. In your m_WebService1_MethodXXCompleted() event handler, you try to update the User Interface (eg. txtBox.text = value)
  5. At this point the screen blows up and you get the dreaded error :

Cross-thread operation not valid: Control ‘Form1’ accessed from a thread other than the thread it was created on

The Reason:

  1. If you are from the old COM/COM+ Days, you must remember that an STA (Single Threaded Apartment) can only be accessed by the thread that originally created it. All the controls on the form are created by the main thread of the application, so only the main thread can update it. When your asynch webservice call returns it is calling the MethodXXCompleted() event handler in the context of a different thread. This thread is not allowed to touch any controls on the form

The Solution :

  1. From the Asynch event handler, you need to invoke the function which will update the UI from the context of the original thread.
  2. code1.jpg
  3. Say, the function which will update the UI is called Private Sub UpdateApps(), you need to declare a delegate for this function. Later we invoke this delegate (see step2 to do the actual work). You cannot call this function directly because it will still happen in the context of the second thread and you will get the same error.
  4. code2.jpg
 

That should take care of the problem. J

Advertisements

38 thoughts on “Cross-thread operation not valid: Control ‘Form1’ accessed from a thread other than the thread it was created on

  1. Hi Nishant,

    I am getting same error “Cross-thread operation not valid: Control ‘Form1′ accessed from a thread other than the thread it was created on” first time i open an application.

    I have created thread which opens splash screen form, then i open login form from splash screen form

    Following is my code snippet:

    Form form;
    delegate void ShowFormDelegate();
    void ShowDialog(Form f)
    {

    form = f;
    //clsLogger.log(f.Handle.ToString());
    //clsLogger.log(f.IsHandleCreated.ToString());
    Form splash = CampaignRoleEditor.Program.objfrmSplash;
    //clsLogger.log(“Invoke Required” + splash.InvokeRequired.ToString());
    clsLogger.log(“Invoke Required f” + f.InvokeRequired.ToString());
    ShowFormDelegate d = new ShowFormDelegate(ShowDialogDelegate);
    //if (f.InvokeRequired == true)
    splash.Invoke(d);
    }
    void ShowDialogDelegate()
    {
    form.ShowDialog();
    }

    I m calling function from following

    Form objfrmLogin = new frmLogin();
    ShowDialog(objfrmLogin);

    Pl let me know , if u find any solution.

    Thanks,
    Gaurav

  2. I’d like to add my code to this article. It took me a while to figure out so I thought it was worth sharing. This sample allows you to update the text on a control, and returns the previous text, so it gives you an example where the delegate function accepts and returns a parameter. Hope it helps!

    A Sample to write text to a Status Bar Panel, and return the original text.

    Old Code:
    public string SetStatusPanel( string strStatus, bool bError )
    {
    try
    {
    strOldStatus = statusBarPanelStatus.Text;
    statusBarPanelStatus.Text = strStatus;
    }
    catch (Exception Ex)
    {
    Debug.WriteLine(Ex.Message);
    }
    return strOldStatus;
    }

    New Code:
    public delegate string StatusPanelDelegate(string strStatus);
    public string SetStatusPanel( string strStatus, bool bError )
    {
    if (this.statusBar.InvokeRequired)
    {
    try
    {
    strOldStatus = Convert.ToString(this.statusBar.Invoke(new StatusPanelDelegate(StatusPanelDelegateSetText), strStatus));
    }
    catch (System.Exception e)
    {
    Debug.WriteLine(e.Message);
    }
    }
    else
    {
    try
    {
    strOldStatus = statusBarPanelStatus.Text;
    statusBarPanelStatus.Text = strStatus;
    }
    catch (Exception Ex)
    {
    Debug.WriteLine(Ex.Message);
    }
    }
    return strOldStatus;
    }
    private string StatusPanelDelegateSetText(string strStatus)
    {
    string strOldStatus = statusBarPanelStatus.Text;
    statusBarPanelStatus.Text = strStatus;
    return strOldStatus;
    }

  3. Nothing seems to be easier than seeing someone whom you can help but not helping.
    I suggest we start giving it a try. Give love to the ones that need it.
    God will appreciate it.

  4. Hi, i’m doing an asynchronous webservice call and I get the Cross-thread operation not valid: “Control ‘Form1′ accessed …” error. I’ve spend all day looking for solution but… hey, it’s your same problem…
    Trying your solution…
    WORKS!!!!!!!
    I own u a beer!

  5. I have tried the same, it has solved the cross thread exception,, but the memory foot print is increased very much.. Any help on why memory utilisation is increased and how to decrease it ??

  6. What’s up, is there anybody else here?
    If it’s not just all bots here, let me know. I’m looking to network
    Oh, and yes I’m a real person LOL.

    Later,

  7. Hi,

    I’ve used this and getting the “Cross-thread operation not valid: Control ” accessed from a thread other than the thread it was created on” exception still

    public partial class Form1 : Form
    {
    delegate Control ControlCreateDelegate();
    private delegate void SetNewControlCallback();
    Control c;

    public Form1()
    {
    InitializeComponent();

    ControlCreateDelegate cdr = new ControlCreateDelegate(CreateMyControl);
    cdr.BeginInvoke(new AsyncCallback(ControlCreationFinished), null);

    }
    Control CreateMyControl()
    {
    return new ClassLibrary1.MyUserControl().CreateMyControl();
    }
    void ControlCreationFinished(IAsyncResult ar)
    {
    int id = Thread.CurrentThread.ManagedThreadId;
    c = cdr.EndInvoke(ar);
    c.Text = String.Format(“Textbox created by thread {0}”, Thread.CurrentThread.ManagedThreadId);
    c.Width = TextRenderer.MeasureText(c.Text, c.Font).Width;
    c.Location = new Point(0, 100);
    this.Invoke( new MethodInvoker(SetNewControl));
    this.EnableButton();
    }
    void SetNewControl()
    {
    int id = Thread.CurrentThread.ManagedThreadId;
    if (InvokeRequired)
    {
    SetNewControlCallback callBack = new SetNewControlCallback(SetNewControl);
    this.Invoke(new MethodInvoker(callBack));
    //return;
    }
    else
    this.panel1.Controls.Add(c); //// <<< Getting error at this line
    }
    }

    Thanks for help.

    -Kathir

  8. Hi I just registered to this exceptional place nishantpant.wordpress.com . I want to ask for your opinion.
    Can you tell me please do you make money with forex and if yes what forex agent do you use?
    Do you know of some good ones?

    Thanks in advance for your answers.

    P.S. Sorry if I have posted to wrong section this but as you can see I am newbie here.

  9. Hello Every body,

    I am new member right here

    I just discovered this place and so far i have discovered lots of great information here.
    I’m looking forward to connecting and adding to the forum.

  10. Доброго времемяни суток!
    Невероятно , но случилось – женюсь!
    вот как Вы на это смотрите?

    з.ы. сорри если не туда написал, имоции 🙂

  11. Hello Every body,

    I am new member right here

    I just discovered this place and so far i have discovered a lot of good info here.
    I’m looking forward to connecting and adding to the forum.

  12. I am getting an exception like below:
    Cross-thread operation not valid: Control ‘Form1’ accessed from a thread other than the thread it was created on.

    Can U solve my problem….

    namespace WindowsFormsApplication2
    {
    public partial class Form1 : Form
    {
    public int WM_SYSCOMMAND = 0x0112;
    public int SC_MONITORPOWER = 0xF170;

    [DllImport(“user32.dll”)]
    private static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);

    public void TrunOFFMonitor(object state)
    {
    SendMessage(this.Handle.ToInt32(), WM_SYSCOMMAND, SC_MONITORPOWER, 2);
    }

    public Form1()
    {
    InitializeComponent();
    }

    private void button1_Click(object sender, System.EventArgs e)
    {

    TimerCallback timCB = new TimerCallback(TrunOFFMonitor);
    SendMessage(this.Handle.ToInt32(), WM_SYSCOMMAND, SC_MONITORPOWER, 2);
    System.Threading.Timer t = new System.Threading.Timer(timCB, null, 0, 1500);

    }

  13. Hi,

    I registered on this dating site Dating Free

    I made several interesting meeting. However I will like to know if you made that meeting and you meet later with the person?

  14. Fantastic blog! I really adore how it? s simple on my eyes also as the information are nicely written. I’m questioning how i may be notified when a new post continues to be created. I’ve subscribed for your rss feed which require to complete the trick! Have a good day!

  15. Guy .. Beautiful .. Amazing .. I will bookmark your web site and take the feeds alsoI am happy to find a lot of useful information here within the submit, we need work out extra techniques on this regard, thanks for sharing. . . . . .

  16. Pretty component to content. I just stumbled upon your web site and in accession capital to claim that I get actually enjoyed account your weblog posts. Any way I will be subscribing on your feeds and even I achievement you get right of entry to constantly quickly.

  17. I’ve been exploring for a little for any high-quality articles or weblog posts in this kind of area . Exploring in Yahoo I eventually stumbled upon this site. Studying this info So i am happy to convey that I’ve a
    very just right uncanny feeling I came upon exactly what I needed.

    I such a lot unquestionably will make certain to don?

    t forget this web site and provides it a
    glance on a relentless basis.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s