Home >Backend Development >C++ >How to Safely Update UI Elements from Non-UI Threads in C#?
Avoid cross-thread errors: Safely update UI elements from non-UI threads
When interacting with UI elements from a non-UI thread (such as the thread spawned by a serial port data reception event), thread safety issues must be handled to avoid cross-thread errors.
In C# code, the error "Invalid cross-thread operation: accessing control 'textBox1' from a thread other than the thread that created control 'textBox1'" occurs because the UI thread owns the textBox1 control, and accessing it from another thread will Causing thread affinity conflicts.
To solve this problem, a scheduler must be used that allows the appropriate thread (usually the UI thread) to access the UI elements. In this case, delegates and the Invoke method can be used to ensure thread-safe access:
<code class="language-csharp">delegate void SetTextCallback(string text); private void SetText(string text) { if (this.textBox1.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { text }); } else { this.textBox1.Text = text; } }</code>
Now, in the serialPort1_DataReceived event handler:
<code class="language-csharp">private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { txt += serialPort1.ReadExisting().ToString(); SetText(txt.ToString()); }</code>
By using the SetText method, you can delegate the task of updating the text property of textBox1 to the UI thread, ensuring safe and error-free access to UI elements from non-UI threads.
The above is the detailed content of How to Safely Update UI Elements from Non-UI Threads in C#?. For more information, please follow other related articles on the PHP Chinese website!