C#, Write to Form TextField from thread
I encountered this problem once when I simple wanted some threads to report their progress to a textfield on the form, This was not a easy as I expected. Since the different threads are not allowed to write to a control object that they do not own.
Instead it can be done as shown in the C# code example below.
private static Form1 instance;
private Object logWindowLock = new Object();
delegate void SetTextCallback(string text);
public Form1()
{
instance = this;
InitializeComponent();
}
public static Form1 Instance
{
get
{
return instance;
}
}
// This method demonstrates a pattern for making thread-safe
// calls on a Windows Forms control.
//
// If the calling thread is different from the thread that
// created the TextBox control, this method creates a
// SetTextCallback and calls itself asynchronously using the
// Invoke method.
//
// If the calling thread is the same as the thread that created
// the TextBox control, the Text property is set directly.
public void WriteToLog(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.logWindow.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(WriteToLog);
this.Invoke(d, new object[] { text });
}
else
{
lock (this.logWindowLock)
{
this.logWindow.AppendText(DateTime.Now.ToString() + ": " + text + "\n");
this.logWindow.ScrollToCaret();
this.logWindow.Refresh();
}
}
}
Hope this make a little sense... I just uploaded the source code during a LBS Privacy lecture. ;)