


C# WinForm multi-thread development (1) Thread class library
Original address: Click to open the link
[Abstract]This article introduces C#
Thread class library for WinForm multi-thread development, and provides simple sample code for reference.
Windows is a multi-tasking system. If you are using Windows 2000 and above, you can use Task Manager View the programs and processes currently running on the system. What is a process? When a program starts running, it is a process. The process refers to the running program and the memory and system resources used by the program. A process is composed of multiple threads. A thread is an execution flow in the program. Each thread has its own private register (stack pointer, program counter, etc.), but the code area is shared, that is, different Threads can execute the same function. Multithreading means that a program contains multiple execution streams, that is, multiple different threads can be run simultaneously in one program to perform different tasks, which means that a single program is allowed to create multiple parallel execution threads to complete their respective tasks.
1 A note about Thread
In the .net framework class library, all classes related to multi-threading mechanism applications are placed in the System.Threading namespace. It provides the Thread class for creating threads, the ThreadPool class for managing thread pools, etc. In addition, it also provides mechanisms to solve practical problems such as thread execution arrangements, deadlocks, and inter-thread communication. If you want to use multithreading in your application, you must include this class. The Thread class has several crucial methods, which are described as follows:
Start(): Start the thread
-
Sleep(int): Static method, pauses the current thread for the specified number of milliseconds
Abort(): Usually use this method To terminate a thread
Suspend(): This method does not terminate the unfinished thread, it only suspends the thread and can be resumed later.
Resume(): Resume the execution of the thread suspended by the Suspend() method
Thread The entrance allows the program to know what to let this thread do. In C#, the thread entrance is provided through the ThreadStart delegate. You can understand ThreadStart as a function pointer, pointing to the function to be executed by the thread. When calling Thread.Start () method, the thread begins to execute the function represented or pointed to by ThreadStart.
The possible values of ThreadState in various situations are as follows:
Aborted: The thread has stopped
-
AbortRequested: The Thread.Abort() method of the thread has been called, but the thread has not stopped yet
Background: The thread is in Background execution, related to the property Thread.IsBackground
Running: The thread is running normally
Stopped: The thread has been stopped
StopRequested: The thread is being asked to stop
Suspended: The thread has been suspended (in this state, it can be re-run by calling the Resume() method)
SuspendRequested: The thread is requesting to be suspended, but will not respond in time
##Unstarted: Thread.Start() is not called to start the running of the thread
- ##WaitSleepJoin:
The thread is in a blocked state because it calls methods such as Wait(), Sleep() or Join()
Two threads used in Winform
First of all, you can look at the most direct method, which is also the method supported under .net 1.0. But please note that this method is already a wrong method after .net 2.0.
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { Thread thread = new Thread(ThreadFuntion); thread.IsBackground = true; thread.Start(); } private void ThreadFuntion() { while (true) { this.textBox1.Text = DateTime.Now.ToString(); Thread.Sleep(1000); } } }
This code throws an exception on vs2005 or 2008: Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on. This is because the security mechanism has been strengthened after .net 2.0 and does not allow direct cross-thread access to the properties of the control in winform. So how to solve this problem? Here are several solutions.
The first option: Set Control.CheckForIllegalCrossThreadCalls to false when Thread is created. This code tells the compiler: In this class, we do not check whether cross-thread calls are legal (if there is no exception when running without adding this sentence, it means that the system adopts the non-checking method by default). However, this approach is not advisable. When we look at the definition of the CheckForIllegalCrossThreadCalls property, we will find that it is static, which means that no matter where we modify this value in the project, it will take effect globally. And we usually check whether there are exceptions in such cross-thread access. If others in the project modify this attribute, then our solution will fail and we will need to adopt another solution.
namespace TestInvoker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(StartSomeWorkFromUIThread));
thread.IsBackground = true;
thread.Start();
//StartSomeWorkFromUIThread();
//label1.Text = "Set value through another thread!";
}
private void StartSomeWorkFromUIThread()
{
if (this.InvokeRequired)
{
BeginInvoke(new EventHandler(RunsOnWorkerThread), null);
}
else
{
RunsOnWorkerThread(this, null);
}
}
private void RunsOnWorkerThread(object sender, EventArgs e)
{
Thread.Sleep(2000);
label1.Text = System.DateTime.Now.ToString();
}
}
}
The above is the content of C# WinForm multi-thread development (1) Thread class library. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

Guide to the Access Modifiers in C#. We have discussed the Introduction Types of Access Modifiers in C# along with examples and outputs.

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

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.

Guide to C# StringReader. Here we discuss a brief overview on C# StringReader and its working along with different Examples and Code.

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.

Guide to C# StringWriter. Here we discuss a brief overview on C# StringWriter Class and its working along with different Examples and Codes.

Guide to BinaryWriter in C#. Here we discuss syntax and explanation, how it works with examples to implement with proper codes.
