I'm writing chat client/server app with c# and I have problem with threading. I wrote this simple code for showing my problem.
I used thread_1 for showing Form but it just show it a second (maybe thread_1 terminated and closed the Form , but i IsAlive said its alive !). Thread_2 try to reach texBox that created on main Thread but it shows me:
"Cross-thread operation not valid: Control 'textBox2' accessed from a thread other than the thread it was created on."
I dont know how solve first problem but I solved second problem with BackgroundWorker but i like to do it with thread. Is there any way?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Thread t1;
Thread t2;
private void button1_Click(object sender, EventArgs e)
{
t1 = new Thread(doThread1);
t1.Name = "thread_1";
t2 = new Thread(doThread2);
t2.Name = "thread_2";
t1.Start();
t2.Start();
MessageBox.Show(t1.IsAlive.ToString());
}
private void doThread1()
{
Form frm2 = new Form();
frm2.Show();
}
private void doThread2()
{
try
{
for (int j = 10000; j > 0; j--)
textBox.Text = j.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}