Updating a TextBox from a Separate Thread in C#
In Windows Forms applications, it's crucial to avoid accessing UI elements from non-UI threads. When attempting to manipulate a TextBox from a separate thread, you may encounter the "This type of operation is not valid on this thread" exception. To address this, you need to properly handle cross-thread communication.
To update a TextBox from a separate thread, you should create a method on your main form that checks for the InvokeRequired property of the Control class. If InvokeRequired is true, it means the call is being made from a non-UI thread, and you need to use the Invoke method to marshal the call to the UI thread.
For example, consider the following code snippet:
public partial class Form1 : Form { public Form1() { InitializeComponent(); new Thread(SampleFunction).Start(); } public void AppendTextBox(string value) { if (InvokeRequired) { this.Invoke(new Action<string>(AppendTextBox), new object[] { value }); return; } ActiveForm.Text += value; } void SampleFunction() { // Gets executed on a separate thread for (int i = 0; i < 5; i++) { AppendTextBox("hi. "); Thread.Sleep(1000); } } }
In this example, the AppendTextBox method checks for the InvokeRequired flag and, if necessary, uses Invoke to marshal the call to the UI thread. Within the SampleFunction method, the AppendTextBox method can be safely called from the separate thread without causing an exception. This approach enables you to update UI elements from non-UI threads while maintaining thread safety.
The above is the detailed content of How to Safely Update a C# TextBox from a Separate Thread?. For more information, please follow other related articles on the PHP Chinese website!