[. Net Object-Oriented programming advanced] (16) multi-threaded (Multithreading) Improve program performance with Multithreading. netmultithreading

Source: Internet
Author: User

[. Net Object-Oriented programming advanced] (16) multi-threaded (Multithreading) Improve program performance with Multithreading. netmultithreading

[. Net Object-Oriented programming advanced] (16) Multithreading improve program performance

This section introduces:

With the rapid development of hardware and network, it provides favorable conditions for multi-thread (Multithreading) to process parallel tasks.

In fact, we are enjoying the convenience of multithreading all the time. multi-core processors work in multiple threads, Windows operating systems, and Web servers all work in multiple threads.

Using multithreading directly improves the execution efficiency of the program. Therefore, it is necessary to learn multithreading to improve the program running capability. This section mainly introduces the multithreading principle and.. NET.. NET application in object-oriented programming.

Before reading: 

This section describes the basics of Lambda expressions, anonymous methods, and anonymous delegation;

A. Delegate [. net Object-Oriented Programming Basics] (20) Delegate 

B. Lamda expressions [. net Object-Oriented programming advanced] (5) Lamda expressions (1) Create Delegation 

1. Multithreading

Before introducing multithreading, let's take a look at the process.

Process: A program that runs independently is called a process. (For example, Windows background programs, also known as background processes)

Thread: a program is divided into multiple execution streams, which are called threads.

Multithreading: multiple threads are used for multi-task processing.

2. How to reasonably use multithreading?

A. Users can use multiple threads to process time-consuming tasks while waiting for processing;

B. You can use background task threads to process tasks that do not need to be completed in real time;

C. You can use multiple threads to process multiple concurrent tasks simultaneously;

D. multithreading can be used for communication classes, such as thread blocking.

In addition to the following common situations, you can also use multithreading in many cases.

3. disadvantages of Multithreading
The thread also has its disadvantages. The following lists some of them:
A. If there are A large number of threads, the performance will be affected because the operating system needs to switch between them;
B. More threads require more memory space;
C. The thread will bring more bugs to the program, so be careful to use it. For example, after the thread task is executed, release the memory in time;
D. The impact of thread suspension on program running must be considered.

4. Two multithreading methods in. NET

. NET itself is a multi-threaded environment.

There are two types of multithreading in. NET:

One is to use the Thread class to create, start, and terminate threads.

One is to use the ThreadPool class to manage the thread pool.

5. Use Thread for multithreading in. NET

5.1 common Thread Methods

The System. Threading namespace of the. NET base class library provides a large number of classes and interfaces that support multithreading. The System. Threading. Thread class is the most common class used to create and control a Thread, set its priority, and obtain its status.

The following are several important methods for this class:
Thread. Start (): the execution of the startup Thread;
Thread. Suspend (): suspends a Thread, or does not work if the Thread has been suspended;
Thread. Resume (): continue the suspended Thread;
Thread. Interrupt (): Stop a Thread in the Wait, Sleep, or Join Thread state;
Thread. Join (): blocks the calling Thread until the end of a Thread.
Thread. Sleep (): the specified number of milliseconds that will block the current Thread;
Thread. Abort (): starts the process of terminating this Thread. If the Thread is already terminated, the Thread cannot be started through Thread. Start.

The following is a simple thread example:

Create a method first:

// Simple thread method static void MyThreadStart () {Console. WriteLine ("I am a simple thread ");}

Method for creating a thread:

// Simple Thread myThread = new Thread (MyThreadStart); myThread. Start ();

The running result is as follows:

5.2Common Thread attributes

There are many attributes of Thread. Let's take a look at the most common attributes:

CurrentThread: used to obtain the current thread;

ThreadState the status of the current thread (5.4 );

Name: gets or sets the thread Name;

Priority: gets or sets the thread Priority (5.5)

ManagedThreadId: gets the unique ID of the current thread.

IsBackground: gets or sets whether the thread is a foreground thread or a background thread (5.6)

IsThreadPoolThread: Gets whether the current thread is a managed thread pool (which will be described later)

The following example creates a thread to describe these attributes:

Thread myThreadTest = new Thread () => {Thread. sleep (1000); Thread t = Thread. currentThread; Console. writeLine ("Name:" + t. name); Console. writeLine ("ManagedThreadId:" + t. managedThreadId); Console. writeLine ("State:" + t. threadState); Console. writeLine ("Priority:" + t. priority); Console. writeLine ("IsBackground:" + t. isBackground); Console. writeLine ("IsThreadPoolThread:" + t. isThreadPoolThread) ;}) {Name = "thread test", Priority = ThreadPriority. highest}; myThreadTest. start (); Console. writeLine ("Number of threads running the associated process:" + System. diagnostics. process. getCurrentProcess (). threads. count );

The running result is as follows:

5.3 thread methods with Parameters 

First, we use Lambda expressions to rewrite the method without parameters in the previous "simple thread", as follows:

// Thread 1 new Thread () => {for (int I = 0; I <5; I ++) Console. writeLine ("My thread 1-[{0}]", I );}). start ();

The running result is as follows:

The thread created in the preceding example does not contain parameters. If there is a parameter method, how should the thread be created?

Don't worry,. NET provides us with a ParameterizedThreadStart delegate to solve the problem with a parameter, as shown below:

// Thread 2 new Thread (num) =>{ for (int I = 0; I <(int) num; I ++) Console. writeLine ("My thread 2 -- [{0}]", I );}). start (5 );

The running result is as follows:

The problem is that the ParameterizedThreadStart delegate only has one parameter containing data. What about multiple parameters? We can use a non-parameter method to wrap it, as shown below:

First, create a method with parameters:

Static void myThreadStart (int numA, int numB) {for (int I = (int) numA; I <(int) numB; I ++) Console. writeLine ("My threads 3 --- [{0}]", I );}

Then wrap it with a delegate without parameters, as shown below:

// Thread 3 new Thread () => myThreadStart (0, 5). Start ();

The running result is as follows:

 

5.4 Thread status

After a thread is started, how can we suspend, terminate, and re-enable the thread? First, the thread has a status after running.

The System. Threading. Thread. ThreadState attribute defines the State of the Thread during execution. A thread must be in one of the statuses from creation to termination.

A. Unstarted:When a thread is created, it is in the Unstarted state.

B. Running:The Start () method of the Thread class changes the Thread state to Running state, and the Thread will remain in this state, unless we call a method to suspend, block, destroy, or terminate it.

C. sushortded:If the thread is Suspended, it will be in the sudedded state.

D. Running:We call the resume () method to re-execute it. At this time, the thread will change to the Running state again. I

E. Stopped:Once the thread is destroyed or terminated, the thread is in the Stopped state. A thread in this state will no longer exist. Just as the thread starts to start, the thread will not be able to return to the Unstarted state.

F. Background:The thread also has a Background status, which indicates whether the thread runs on the foreground or Background. At a specified time, the thread may be in multiple States.

G. WaitSleepJoin, AbortRequested:For example, if a thread is blocked when Sleep is called, and another thread calls the Abort method, the thread is in both WaitSleepJoin and AbortRequested states.

H. Once the thread response is converted into a blocking or suspension of the system shell, a ThreadAbortException exception will be thrown when the thread is destroyed.

The 10 invocation statuses of ThreadState enumeration are as follows:

 

For thread blocking and synchronization problems, we will continue to introduce them in the next section.

5.5. thread priority

For a multi-threaded task, we can set its priority based on its importance and resources required for running.
System. Threading. ThreadPriority enumerates the priority of a thread, which determines how much CPU time the thread can obtain.

High-priority threads usually get more CPU time than general-priority threads. If there are more than one high-priority thread, the operating system will allocate CPU time cyclically between these threads.

Low-priority threads get less CPU time. When there is no high-priority thread, the operating system selects the next low-priority thread for execution.

Once a low-priority thread encounters a high-priority thread during execution, it will give the CPU to the high-priority thread.

The priority of the newly created thread is normal. We can set the priority value of the thread, as shown below:

For the thread priority, we will conduct an experiment below to enable two threads (one setting high priority and the other setting low priority ).

Run the following two methods to accumulate the result:

Int numberA = 0, numberB = 0; bool state = true; new Thread () => {while (state) numberA ++ ;}) {Priority = ThreadPriority. highest, Name = "thread "}. start (); new Thread () => {while (state) numberB ++ ;}) {Priority = ThreadPriority. lowest, Name = "thread B "}. start (); // Let the main Thread pendant Thread for 1 second. sleep (1000); state = false; Console. writeLine ("thread A: {0}, thread B: {1}", numberA, numberB );

The running result is as follows:

. NET allocates resources based on the priority. It can be seen that the thread with a higher priority has a higher chance of execution, but the thread with a lower priority still has a higher chance of execution.

5.6 foreground thread and background thread

There are two types of threads, which are foreground threads by default. To set them as background threads, you only need to add a property: thread. isBackground = true; it can be changed to a background thread.

The point is, the difference between the frontend and backend threads:

A. Foreground thread: The application can exit only after all foreground threads are executed;

B. Background threads: applications can exit directly without having to consider whether they are all completed. The background thread is automatically terminated when the application exits.

Next we will use a number from 0 to 1000 to test the difference between the foreground thread and the background thread:

Thread myThread = new Thread(() =>{for (int i = 0; i < 1000; i++)Console.WriteLine(i);});         var key = Console.ReadLine();if (key == "1"){    myThread.IsBackground = true;    myThread.Start();}else{    myThread.IsBackground = false;    myThread.Start();}

When we enter the level in the console,

If the input is 1 (the background thread), the thread will soon be closed and will not be closed after the output reaches 1000 digits;

If other values are input, press enter to close the window after the thread waits for 1000 numbers to be output;

6. Highlights of this section:

A. This section describes the basic knowledge of threads;

B. common attributes and methods of Thread;

C. The method entrusted by the Thread has the usage of multiple parameters;

D. Thread priority;

E. Thread execution status;

F. foreground and background threads;

We will continue to introduce how to use threads to improve program performance later.

========================================================== ========================================================== ====================

Returned directory

<If it is helpful to you, remember to clickRecommendationOh, if you have any questions or errors, please contact us more>

<If you have any difficulties reading this series of articles, please read them first.. Net Object-Oriented Programming Basics>

<Reprinted statement: technology requires a spirit of sharing. You are welcome to repost the article in this blog, but please note the copyright and URL>

. NET exchange group: 467189533

========================================================== ========================================================== ====================

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.