Cross-thread operation not valid – error solved in C#

For the beginners, working on thread might come across the error saying “Cross-thread operation not valid“. This type error comes normally when Windows control created in one thread and accessed in another.
Because the Windows control are not thread safe by default.

ThreadCommunication
Thread Communication

The best way to solve this kind of error is :

if (InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                       //Your code here, like set text box content or get text box contents etc..
                    }));
                }
                else
                {
                     // Your code here, like set text box content or get text box contents etc..
                     // SAME CODE AS ABOVE
                }

Posted

in

,

by

Tags:


Related Posts

Comments

3 responses to “Cross-thread operation not valid – error solved in C#”

  1. neha Avatar
    neha

    This worked! Thank you for a simple explanation.

  2. Steve Avatar
    Steve

    Fantastic! Works as intended with concise explanation! Saved me probably couple of hours of searching.

  3. Michael Blankenship Avatar
    Michael Blankenship

    It works! Thank You

    I wish understood why it works?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading