How to Write to a TextBox from Another Thread in a C# Windows Form Application
In a C# Windows Form application, modifying the contents of a TextBox from a thread other than the UI thread can lead to threading issues. To address this, it's essential to understand the concept of thread safety.
Understanding Thread Safety
Thread safety refers to the ability of a code block or object to be executed concurrently by multiple threads without causing unintended side effects. In the context of a Windows Form application, the UI controls, including TextBoxes, are not thread-safe. Attempting to update their properties from a non-UI thread can result in exceptions or unexpected behavior.
Solution: Invoking Control Methods
To safely modify UI elements from a separate thread, you must invoke their methods using the Invoke or BeginInvoke methods of the control. These methods ensure that the operation is marshaled to the UI thread, which is the only thread that can safely interact with the controls.
Code Sample
Consider the following code sample that demonstrates writing to a TextBox from a separate thread using the Invoke method:
public partial class Form1 : Form { public Form1() { InitializeComponent(); new Thread(SampleFunction).Start(); } public void AppendTextBox(string value) { if (InvokeRequired) { // Invoke the AppendTextBox method if the current thread is not the UI thread. this.Invoke(new Action<string>(AppendTextBox), new object[] { value }); return; } textBox1.Text += value; } void SampleFunction() { for (int i = 0; i < 5; i++) { AppendTextBox("hi. "); Thread.Sleep(1000); } } }
In this code:
The above is the detailed content of How to Safely Update a C# Windows Forms TextBox from a Non-UI Thread?. For more information, please follow other related articles on the PHP Chinese website!