sorry for the bad presentation before. I edited the code and now it gives me the required result. So now when a thread writes in the richtextbox, the other threads do not freeze. I don't know whey I don't need to refresh the richtextbox her after adding a character! However, I'm still confused. Sometimes when I don't use Invoke method with any control I got an error, but now, as u can see in
panel.BackColor = Color.Red;
The compiler did not complain. Why?
namespace ThreadGUI
{
public partial class Form1 : Form
{
private Size s = new Size(50, 50);
Point p;
public Form1()
{
InitializeComponent();
}
private void Form1_MouseClick(object sender, MouseEventArgs e)
{
p = new Point(e.X, e.Y);
Thread th = new Thread(new ThreadStart(DoWork));
th.Start();
}
public void DoWork()
{
Panel panel = new Panel();
Form1 frm = new Form1();
Point p1 = new Point(p.X - 25, p.Y - 25);
panel.Location = p1;
panel.Size = s;
panel.BackColor = Color.BlueViolet;
this.Invoke(new MethodInvoker(delegate { this.Controls.Add(panel); }));
Random ri = new Random();
while (true)
{
panel.BackColor = Color.BlueViolet;
int ti = ri.Next(500);
while (ti > 0)
{
int xi = ri.Next(2) * 10 - 5;
int yi = ri.Next(2) * 10 - 5;
Thread.Sleep(10);
p1.X += xi;
p1.Y += yi;
panel.Invoke(new MethodInvoker(delegate { panel.Location = p1; }));
ti--;
}
panel.BackColor = Color.Red;
lock ("jkj")
{
panel.BackColor = Color.Green;
string str = "I am a thread";
foreach (char c in str.ToCharArray())
{
richTextBox1.Invoke(new MethodInvoker(delegate { richTextBox1.AppendText(c.ToString()); }));
Thread.Sleep(100);
}
}
}
}
}
}