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
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
namespace WindowsFormsApplication1
{
class Class1
{
public Form1 fm = new Form1();
public static void start()
{
Form1 fs = new Form1();
fs.UpdateTxt("test");
}
}
}