Monday 19 May 2014

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


When you are using threading in your winform application and accessing form controls in method that is called in new thread, then you will face error like below :

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

Here is solution for this error. You have to invoke your form again to access controls. Here is snippet for that.


       private void button1_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(setText);
            th.Start();

        }

        public delegate void delTemp();
        public void setText()
        {
            if (this.InvokeRequired)
            {
                delTemp del = new delTemp(setText);
                this.Invoke(del);
                return;
            }
            label1.Text = "This is set from thread";
        }



No comments:

Post a Comment