It's still throwing a cross-threading exception? Or am I missing the point of what the problem is here?
If you're creating the server object in your form class, and then you're trying to access the form's textbox from the server object, then you need to use an event. However, even if this is the case, you will still need to invoke the textbox as you're accessing it from a child thread!
Here's a little demo I made for you to explain what I mean. Ok so I made a form and dropped a TextBox onto it, and then added a Load event to the Form. I then made an object called MyServer:
Code:
using System;
using System.Threading;
namespace WindowsApplication13
{
class MyServer
{
public delegate void MyLoggingDelegate(String text);
public event MyLoggingDelegate OnLogTextAdding;
private Thread my_thread;
public void Start()
{
this.my_thread = new Thread(new ThreadStart(this.ThreadWorker));
this.my_thread.Start();
}
private void ThreadWorker()
{
while (true) // send test message every 1 second
{
OnLogTextAdding("this is a test message!");
Thread.Sleep(1000);
}
}
}
}
It's not a real server, but when Start() is executed it will try to send a test message back to the form's textbox every 1 second.
Add this code to the form:
Code:
using System;
using System.Windows.Forms;
namespace WindowsApplication13
{
public partial class Form1 : Form
{
private MyServer my_server;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.my_server = new MyServer();
this.my_server.OnLogTextAdding += new MyServer.MyLoggingDelegate(this.OnLogTextAdding);
this.my_server.Start();
}
private void OnLogTextAdding(String text)
{
if (this.textBox1.InvokeRequired) // are we cross threading?
{
this.textBox1.BeginInvoke(new MyServer.MyLoggingDelegate(this.OnLogTextAdding), text);
}
else
{
this.textBox1.Text += (text + "\r\n"); // add new text plus line break
this.textBox1.SelectionStart = this.textBox1.Text.Length; // stop the new text being highlighted
this.textBox1.ScrollToCaret(); // keep it scrolled down
}
}
}
}