0

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)";           
            }
        }

Edited by Lolalola: n/a

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by Lolalola
0

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;
    }
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.