Hi,
my program don't work?
Propgram stop on: this.textBox1.Text = "(New text)";

Thread demoThread;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.demoThread = new Thread(new ThreadStart(this.ThreadProcUnsafe));
            this.demoThread.Start();

            textBox1.Text = "Written by the main thread.";
        }

        private void ThreadProcUnsafe()
        {
            while (true)
            {
                Thread.Sleep(2000);

                this.textBox1.Text = " (New new)";           
            }
        }

Recommended Answers

All 2 Replies

You need to be in the main thread to set the text. Try something like this modification of your code.

private void Form1_Load(object sender, EventArgs e)
{
    Thread demo = new Thread(new ThreadStart(this.ThreadProc));
    demo.Start();
    SetText("Main thread");
}

private void ThreadProc()
{
    while (true)
    {
        Thread.Sleep(1000);

        SetText(DateTime.Now.ToString());
    }
}

private void SetText(string input)
{

    if (this.textBox1.InvokeRequired)
    {
        Action<string> action = SetText;
        this.Invoke(action, input);
    }
    else
    {
        this.textBox1.Text = input;
    }
}

thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.