Home > Backend Development > C++ > How to Safely Update a TextBox from a Serial Port in C#?

How to Safely Update a TextBox from a Serial Port in C#?

DDD
Release: 2025-01-23 02:13:07
Original
286 people have browsed it

How to Safely Update a TextBox from a Serial Port in C#?

Solving the Cross-Thread Exception When Updating a TextBox from a Serial Port in C#

A common problem in C# serial communication involves updating a TextBox from the serialPort1_DataReceived event handler. Because the serial port operates on a separate thread, directly accessing the TextBox from this event handler throws a "Cross-thread operation not valid" exception.

The solution requires a thread-safe method to update the TextBox's text. This is achieved by marshaling the update back to the UI thread. Here's how:

<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

This SetText method checks if the current thread is the UI thread (textBox1.InvokeRequired). If not, it uses Invoke to marshal the SetText call back to the UI thread, ensuring thread safety. Otherwise, it updates the TextBox directly.

Here's how to integrate this into your serialPort1_DataReceived event handler:

<code class="language-csharp">private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
    string receivedData = serialPort1.ReadExisting();
    SetText(receivedData); // Use the thread-safe SetText method
}</code>
Copy after login

This revised event handler reads data from the serial port and uses the SetText method to safely update the TextBox, preventing the cross-thread exception. This approach guarantees that UI updates are always performed on the correct thread, maintaining application stability.

The above is the detailed content of How to Safely Update a TextBox from a Serial Port 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template