Click here to Skip to main content
15,907,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a problem when updating textbox which is called from different thread.
I have two classes in different .cs files (Form1.cs and Class1.cs).

In Form1.cs, there are button and textbox controls. The flow is simply like this:
1. Click button
2. Create and start new thread

In Class1.cs, the flow is even simpler:
1. Run a function which is writing a text into textbox control of Form1.

Problem:
1. "test" won't print out in textbox.
2. InvokeRequired is always false, have no idea why?

This may be a simple and stupid question but annoying me for a long time, please kindly advice.
Thank you all.

Two cs files are posted as follows:

Form1.cs
C#
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(new ThreadStart(Class1.start));
            th.Start();
        }

        public void UpdateTxt(string str)
        {
            if (InvokeRequired)
            {

                this.Invoke(new Action<string>(UpdateTxt), new object[] { str });
                return;
            }
            textBox1.AppendText(str + "\n");
        }
    }
}


Class1.cs
C#
namespace WindowsFormsApplication1
{
    class Class1
    {
        public Form1 fm = new Form1();

        public static void start()
        {
            Form1 fs = new Form1();
            fs.UpdateTxt("test");
        }
    }
}
Posted
Updated 4-Jun-13 23:56pm
v2

You're creating new Form1's with every call to Class1.start().
Use the instance instead, that is created in Program.cs in the line
C#
Application.Run(new Form1());
Usually, you would Class1 let fire an event that UpdateText() reacts to.
 
Share this answer
 
v2
Hi lukeer, as you said, I used event and it worked.
Thanks a lot!
 
Share this answer
 
Comments
lukeer 7-Jun-13 1:37am    
In this case, you're supposed to (1) upvote and/or (2) accept my solution and/or (3) leave a comment in the solution's comment section.
That way, (1) I get some reputation points, which helps keeping me motivated to answer people's questions.
(2) gets me even more rep points and marks the question as solved, which helps forum readers to decide whether they need to open the question or not.
(3) will automatically inform me that someone commented on something I wrote.

You're not supposed to post this as a solution, simply because it is not a solution. And I checked by only by chance (see (3)).

That's how this forum works. And on the subject: Thanks for the feedback. I'm glad of having been of some help.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900