Home Backend Development C#.Net Tutorial Self-study C#02 from 0--child thread accesses main thread (UI thread) control

Self-study C#02 from 0--child thread accesses main thread (UI thread) control

Feb 04, 2017 am 10:33 AM

If you use multithreading to improve the performance of a Windows Forms application, you must ensure that controls are called in a thread-safe manner.

Accessing Windows Forms controls is not inherently thread-safe. If you have two or more threads manipulating a control's state, you may force the control into an inconsistent state. Other thread-related bugs may occur, such as race conditions and deadlocks. Be sure to access controls in a thread-safe manner.

1. Problems often encountered by beginners

It is unsafe to call a control from a thread that has never used the Invoke method to create the control. Below is an example of a non-thread-safe call. An InvalidOperationException message will be thrown during runtime, with the error "The control control name is accessed from a thread that did not create the control."

// This event handler creates a thread that calls a // Windows Forms control in an unsafe way.private void setTextUnsafeBtn_Click(    object sender, 
    EventArgs e)
{    this.demoThread = 
        new Thread(new ThreadStart(this.ThreadProcUnsafe));    this.demoThread.Start();
}// This method is executed on the worker thread and makes// an unsafe call on the TextBox control.private void ThreadProcUnsafe()
{    this.textBox1.Text = "This text was set unsafely.";
}
Copy after login


2. Solution

If you need to make thread-safe calls to Windows Forms controls.

①Query the InvokeRequired property of the control.

②If InvokeRequired returns true, use the delegate of the actual calling control to call Invoke.

③If InvokeRequired returns false, please call the control directly.

Here are divided into synchronous execution delegation and asynchronous execution delegation.

Self-study C#02 from 0--child thread accesses main thread (UI thread) control

In the following code example, thread-safe invocation is implemented in the ThreadProcSafe method, which is executed by a background thread. If the TextBox control's InvokeRequired returns true, the ThreadProcSafe method creates a SetTextCallback instance and passes it to the form's Invoke method. This causes the SetText method to be called on the thread that created the TextBox control, and the Text property to be set directly in the context of that thread.

// This event handler creates a thread that calls a 
// Windows Forms control in a thread-safe way.
private void setTextSafeBtn_Click(    
object sender, 
    EventArgs e)
{    this.demoThread = 
        new Thread(new ThreadStart(this.ThreadProcSafe));    
this.demoThread.Start();
}// This method is executed on the worker thread and makes
// a thread-safe call on the TextBox control.
private void ThreadProcSafe()
{    this.SetText("This text was set safely.");
}// This delegate enables asynchronous calls for setting
// the text property on a TextBox control.delegate void SetTextCallback(string text); 
// This method demonstrates a pattern for making thread-safe
// calls on a Windows Forms control. 
//
// If the calling thread is different from the thread that
// created the TextBox control, this method creates a
// SetTextCallback and calls itself asynchronously using the// Invoke method.
//
// If the calling thread is the same as the thread that created
// the TextBox control, the Text property is set directly. private void SetText(string text)
{    // InvokeRequired required compares the thread ID of the
    // calling thread to the thread ID of the creating thread.
    // If these threads are different, it returns true.
    //this.textBox1.InvokeRequired will be replaced by
    //this.InvokeRequired, if want to set many controls' 
    //attribute or text.
    if (this.textBox1.InvokeRequired)// or this.InvokeRequired
    {   
        SetTextCallback d = new SetTextCallback(SetText);        
this.Invoke(d, new object[] { text });
    }    else
    {        this.textBox1.Text = text;
    }
}
Copy after login

3.BackgroundWorker component

The preferred way to implement multi-threading in an application is to use the BackgroundWorker component. The BackgroundWorker component uses an event-driven model for multi-threaded processing. The background thread runs your DoWork event handler, and the thread that created your control runs the ProgressChanged and RunWorkerCompleted event handlers. You can call controls from ProgressChanged and RunWorkerCompleted event handlers.

①Create a method to do the work you want to do in the background thread. Do not call controls created from the main thread in this method.

②Create a method to report the background work results after the background work ends. Controls created by the main thread can be called in this method.

③Bind the method created in step 1 to the BackgroundWorker event in the DoWork instance, and bind the method created in step 2 to the RunWorkerCompleted event of the same instance.

④To start a background thread, call the BackgroundWorker method of the RunWorkerAsync instance.

In the following code example, the DoWork event handler uses Sleep to simulate work that takes some time. It does not call the form's TextBox control. The TextBox control's Text property is set directly in the RunWorkerCompleted event handler.

// This BackgroundWorker is used to demonstrate the 
// preferred way of performing asynchronous operations.private BackgroundWorker backgroundWorker1; 
// This event handler starts the form's // BackgroundWorker by calling RunWorkerAsync.
//
// The Text property of the TextBox control is set
// when the BackgroundWorker raises the RunWorkerCompleted
// event.private void setTextBackgroundWorkerBtn_Click(    
object sender, 
    EventArgs e)
{    this.backgroundWorker1.RunWorkerAsync();
}// This event handler sets the Text property of the TextBox
// control. It is called on the thread that created the 
// TextBox control, so the call is thread-safe.
//
// BackgroundWorker is the preferred way to perform asynchronous
// operations.private void backgroundWorker1_RunWorkerCompleted(    
object sender, 
    RunWorkerCompletedEventArgs e)
{    this.textBox1.Text = 
        "This text was set safely by BackgroundWorker.";
}
Copy after login

You can also report the progress of background tasks by using the ProgressChanged event. For an example that includes this event, see BackgroundWorker.

The above is the content of self-study C#02 from 0--child thread accessing the main thread (UI thread) control. For more related content, please pay attention to the PHP Chinese website (www.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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

C# Serialization C# Serialization Sep 03, 2024 pm 03:30 PM

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Prime Numbers in C# Prime Numbers in C# Sep 03, 2024 pm 03:35 PM

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

Factorial in C# Factorial in C# Sep 03, 2024 pm 03:34 PM

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

See all articles