0

Possible Duplicate:
How to update GUI from another thread in C#?

I have form with textBox1 and textBox2. I need very simple example of an extra thread to fill textBox2, just to understand principle. So far i am using MessageBox to display value, but i want to use textBox2 instead. Here is my code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Threads_example
{
    public partial class Form1 : Form
    {
        Thread t = new Thread(t1);
        internal static int x1 = 1;


        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }


        static void t1()
        {
            do
            {
                x1++;
                MessageBox.Show("x1 - " + x1.ToString());
            }
            while(x1<10);
        }


        private void button1_Click(object sender, EventArgs e)
        {

            t.Start();

            for (int x = 1; x < 100000; x++)
            {
                textBox1.Text = x.ToString();
                textBox1.Refresh();
            }
        }

    }
}
Community
  • 1
  • 1
Cembo
  • 41
  • 2
  • 4
  • 2
    Threads cannot access UI components directly. You need to use `Control.Invoke`. A search here or via Google should reveal many examples. – ChrisF Jan 15 '12 at 17:38

1 Answers1

0

You need to invoke UI actions in the GUI thread. It can be done with something like this:

private void RunFromAnotherThreadOrNot()
{
           if (InvokeRequired)
           {
               Invoke(new ThreadStart(RunFromAnotherThread));
               return;
           }


           textBox2.Text = "What Ever";
           // Other UI actions

}
Lior Ohana
  • 3,467
  • 4
  • 34
  • 49