-1

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):

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.'

PrestonDj
  • 3
  • 3
  • https://stackoverflow.com/questions/661561/how-do-i-update-the-gui-from-another-thread – Kroepniek Aug 01 '23 at 11:48
  • @Selvin Before making the post, stack overflow literally says "do any of these match your question", none of them did and so I made the post. I had also checked stack overflow for the question, and was unable to understand any of the answers, hence i asked here, because as you and I both stated, I'm new to C# – PrestonDj Aug 01 '23 at 11:50
  • *wasn't able to find anything of my own accord* ... please ... what returns internet search for "System.InvalidOperationException: Cross-thread operation not valid" ... – Selvin Aug 01 '23 at 11:51

1 Answers1

0

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;
}
Mustafa Özçetin
  • 1,893
  • 1
  • 14
  • 16