Hi. I'm working on a chat program, and I'm having some trouble with the thread that is supposed to get text from a file and append it to a rich text box that acts as the chat display. The problem arises when I attempt to edit the textbox text from the thread, I get this error:
Code:
Control 'richTextBox1' accessed from a thread other than the thread it was created on.
Here is the thread's function:
Code:
private void Thread_get_text()
{
string text = "";
string new_text = "";
while (true)
{
StreamReader read = new StreamReader("chat.log");
new_text = read.ReadLine();
if (text != new_text)
{
text = new_text;
read.Close();
richTextBox1.Text = text;
}
read.Close();
Thread.Sleep(10);
}
}
Now, I understand that I'm supposed to use a delegate here, but I don't quite understand how to use one. I looked at MSDN's delegate tutorial and followed their example, and I ended up with this:
Code:
//declaration
private delegate void Del(string text);
//AppendText definition
private void AppendText(string text)
{
richTextBox1.Text = text;
}
private void Thread_get_text()
{
Del handler = AppendText;
string text = "";
string new_text = "";
while (true)
{
StreamReader read = new StreamReader("chat.log");
new_text = read.ReadLine();
if (text != new_text)
{
text = new_text;
read.Close();
handler(text);
}
read.Close();
Thread.Sleep(10);
}
}
This prompts the same error message: Control 'richTextBox1' accessed from a thread other than the thread it was created on.
What did I do wrong with the delegate? Is this even the correct approach to fixing my problem?