-1

Possible Duplicate:
Cross-thread operation not valid

My function I put to new thread, but it doesn't work. I have exception:

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

My code:

    void licz()
    {
        int wynik = 0;
        for (int i = 0; i < 200; i++)
        {

            wynik =+ i;
            textBox1.Text += wynik.ToString() + Environment.NewLine;

        }
        MessageBox.Show("Wynik: " + wynik);
    }

    public Form1()
    {
        InitializeComponent();
    }

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


    }

How fix it?

Community
  • 1
  • 1
user1031034
  • 836
  • 1
  • 14
  • 38

1 Answers1

1

You can't access UI Elements from another thread than the one that created it (the UI thread). Your alternatives would be to use a callback, raise an event that your UI thread is subscribed to or use the Dispatcher if you're working with WPF or Silverlight.

If you give more details on what you're trying to achieve and the technology you're using I could give a more complete answer.

dee-see
  • 23,668
  • 5
  • 58
  • 91