-1

This is my first project on threading but i'm lost.. The problem is: I want to make a second counter, where every prime number turn color.

Thread thread1;
private void Form1_Load(object sender, EventArgs e)
{
    thread1 = new Thread(new ThreadStart(voidPrime));
}

int sec=0;

void voidPrime()
{

    sec+= 1;
    label1.Text = sec.ToString();
    if (isprime(int.Parse(label1.Text)))
    {
        label1.ForeColor = Color.RED;
    }
    else 
    {
        label1.ForeColor = Color.Black;
    }
}

private void PLAY_Click(object sender, EventArgs e)
{
    thread1.Start();

    while (thread1.IsAlive)
    {
        Thread.Sleep(1000);
    }
}

When I start and press the PLAY button, throws me

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

halfer
  • 19,824
  • 17
  • 99
  • 186
Sparkle
  • 21
  • 5
  • Controls cannot be touched/modified by another thread, only the UI thread can access them, you will need to `Invoke` your call back to the UI thread so it wont thow an exception – sa_ddam213 Aug 27 '14 at 01:20
  • 4
    You're going to be stuck on this for like many more days, because you can't do what you're attempting to do. The error message explains **exactly** what the problem is: "Control 'label2' accessed from a thread other than the thread it was created on." - this clearly says you can't access a control **from a thread other than the thread it was created on**, which means you **cannot access it from a different thread**. It's always important to **read the words** in error messages - they almost always mean something. – Ken White Aug 27 '14 at 01:30

1 Answers1

1

Only the UI thread can directly modify a Winform Control.

Easiest way to do this is use a background worker (It is a Winform Control) eg.

private void PLAY_Click(object sender, EventArgs e) 
{
    isPrime=false;
    bwHILO.RunWorkerAsync(segundos);
}

private bwHILO_DoWork(object sender, DoWorkEventArgs e)
{
   bool isPrime = ESPrimo((int) e.Argument);
   e.Result=isPrime;
}

private bwHILO__RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
   bool result = (bool)e.Result;
  if(result)
  {
    label2.ForeColor = Color.Maroon;
  } 
  else
  {
    label2.ForeColor = Color.Black;
   }
}
mikek3332002
  • 3,546
  • 4
  • 37
  • 47