Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to change the attributes of a label from within a specific thread on C# (Windows Forms App)

I’m new to C# so take it easy on me please, but I’m running into a problem where I’m unable to change the state of the visibility of a label within a thread that I’ve made.

The label I’m trying to change is called DEBUG, and isn’t related in any way to Label1

Here is the code for the form (DebugCount is an integer that is defined in the code for the form itself):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public partial class GamePage : Form
    {
        public GamePage()
        {
            InitializeComponent();

            Thread DebugThread = new(new ThreadStart(DebugHandler));
            DebugThread.Start();
        }
        
        private void label1_Click(object sender, EventArgs e)
        {
            DebugCount++;
        }

        public void DebugHandler()
        {
            while(true)
            {
                if(DebugCount >= 5)
                {
                    DEBUG.Visible = true;
                    break;
                }
            }
        }
     }

Here is the error:
System.InvalidOperationException: ‘Cross-thread operation not valid: Control ‘GamePage’ accessed from a thread other than the thread it was created on.’

>Solution :

You can use the Control.Invoke() method with MethodInvoker. It allows you to execute a code segment from another thread on the UI thread:

if (DebugCount >= 5)
{
    DEBUG.Invoke((MethodInvoker)delegate 
    {
        DEBUG.Visible = true;
    });
    break;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

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

Continue reading