Home > Backend Development > C++ > How to Safely Update a C# TextBox from a Separate Thread?

How to Safely Update a C# TextBox from a Separate Thread?

Barbara Streisand
Release: 2024-12-31 20:37:13
Original
349 people have browsed it

How to Safely Update a C# TextBox from a Separate Thread?

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);
        }
    }
}
Copy after login

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!

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