Home > Backend Development > C++ > How to Safely Update UI Elements from Non-UI Threads in C#?

How to Safely Update UI Elements from Non-UI Threads in C#?

Susan Sarandon
Release: 2025-01-23 02:14:15
Original
247 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template