. Net brief introduction to component programming (first knowledge of. Net thread)

Source: Internet
Author: User
Tags net thread

I will use a few articles because of the many threads.Article.

Multithreading is widely used in our daily development process.. NET componentsProgramDesign (asynchronous delegation) This article describes in detail how to use multiple threads Based on delegation. Delegation is based on the principle of backend thread pools. This article mainly introduces how to use thread objects to implement multiple threads.

Of course, using thread is not as easy as using delegate. After all, multithreading and asynchronous calling are two very different technical directions. I also have a little bit of knowledge and I am sorry to give it to you here, if anything is wrong, please point it out.[Wang qingpei has all rights reserved. For more information, please sign it.]

Let's first understand several concepts to facilitate our learning.

Background thread and foreground thread

Foreground thread: What is foreground thread, that is, the foreground thread is created using the default thread without setting the isbackground attribute, because the default isbackground is false. The foreground thread specifies the task, that is, the program will not automatically exit before any foreground thread ends, unless the application is forcibly closed.

Background thread: the background thread is for the foreground thread. if isbackground is set to true, It is the background thread, and the background thread serves the foreground thread. That is to say, the background thread does not have a strong vitality. As long as the foreground thread ends, the background thread ends forcibly, even if the task is not completed. Therefore, we should select the actual situation when using it.[Wang qingpei has all rights reserved. For more information, please sign it.]

Thread Switching

Let's take a lookCodeTo facilitate topic introduction.

 
Using system; using system. collections. generic; using system. text; using system. threading; using system. runtime. remoting; using system. runtime. remoting. contexts; namespace consoleapplication1. multithreading and concurrency management {public class myclass {public void showmessage () {thread currentthread = thread. currentthread; console. writeline (currentthread. name + currentthread. managedthreadid );}}}

 

This is a simple piece of code. It is a showmessage method. There is a static attribute thread. currentthread in the method to get the current context thread, and then enter the thread name and managed ID;

Namespace consoleapplication1. multithreading and concurrency management {public static class program {static void main (string [] ARGs) {thread currentthread = thread. currentthread; currentthread. name = "main thread"; console. writeline (currentthread. name + currentthread. managedthreadid); myclass = new myclass (); threadstart start = new threadstart (myclass. showmessage); thread = new thread (start); thread. name = "subthread"; thread. start (); thread. sleep (1000); // sleep, the thread switches to the console. writeline (currentthread. name + currentthread. managedthreadid); console. read ();}}}

 

This is the call code. I will give the main thread a name and then output it. I created a thread. This is a subthread. We call the method defined above and use the same thread. currentthread to obtain the current context thread. At last, let the main thread sleep for one second.

The figure clearly shows that the system automatically switches the thread in the background and obtains the current thread object using the same static variable.

The sleep method is used to break the current thread for sleep at a specified time. Even if the current thread is running on the CPU, the system immediately discards the time slice that the CPU has given it once sleep is called and enters the blocking state.

[A thread is only the execution path in a process]

In fact, the thread is the execution path, and the system maintains a set of commands for the execution path, when multiple threads are enabled, we actually store a lot of commands to be executed in a command set. In other words, the commands are thread queues, use the CPU to execute the time slice.

Then the thread must be in a series of states, which are maintained by the OS, because the thread is an object at the kernel layer and can only be monitored by the OS in real time. We only need to use it. If you are interested, you can refer to Jeffrey Richter, Windows core programming (version 5th.

Let the thread wait rather than Switch

Sleep forces you to discard the CPU time slice and repeat it with other threads to compete with the CPU. Using sleep will give up the CPU usage right for the thread, and if we change to thread. spinwait (100000000) won't give up the CPU's right to use. It just allows the CPU to execute a piece of useless code. After the time is over, it can be executed immediately, instead of competing with the CPU again.

This may not be important when the system resources are rich, but when the resources are insufficient and the CPU is not very good, I think this can improve the performance.

An important concept has to be put forward here: the caller of the thread and the main body of the thread. The caller of the thread is the client of the thread and another thread, rather than the current thread.

Thread. Join () connection thread

The join method literally refers to the meaning of the connection. It is really hard to understand what the join method is. See the following code:

 
Thread currentthread = thread. currentthread; currentthread. name = "main thread"; console. writeline (currentthread. name + currentthread. managedthreadid); myclass = new myclass (); threadstart start = new threadstart (myclass. showmessage); thread = new thread (start); thread. name = "subthread"; thread. start (); thread. join (); // block the sub-thread until the sub-thread execution ends. writeline (currentthread. name + currentthread. managedthreadid); console. read ();

 

Through join, we can wait for the thread to end. The connection means to connect me to the thread I called. I will continue to execute it after the end of the thread, here is the relationship between the main thread and the sub-thread. Only after the sub-thread technology, the main thread can continue to execute.

Thread. Abort terminate the thread

Abort can be used to terminate a thread in execution, but abort will cause a threadabortexception exception on the thread.

Public void dowork () {try {int I = 0; while (true) {console. writeline (thread. currentthread. managedthreadid + "|" + I ++); if (I = 100) {console. writeline ("---------------------------------------------"); console. read (); break; // exit the current thread for execution. Try not to end with abort }}catch (threadabortexception ERR) {console. writeline (err. message + "11 ");}}

 

Thread currentthread = thread. currentthread; console. writeline (currentthread. name + currentthread. managedthreadid); myclass = new myclass (); threadstart start = new threadstart (myclass. dowork); thread = new thread (start); thread. start (); thread. sleep (1, 5000); console. writeline (currentthread. name + currentthread. managedthreadid + "end-to-end sub-thread"); thread. abort (); console. read ();

 

Thread. isbackground = true background thread

By setting isbackground, the thread can be placed in the background thread. As long as the foreground thread ends, the background thread is automatically terminated.

Public void dowork () {try {int I = 0; while (true) {console. writeline (thread. currentthread. managedthreadid + "|" + I ++); // if (I = 100) // {// console. writeline ("---------------------------------------------"); // console. read (); // break; // exit the current thread for execution. Try not to end with abort //} catch (threadabortexception ERR) {console. writeline (err. message + "11 ");}

 

 

Comment out a piece of code.

Thread currentthread = thread. currentthread; console. writeline (currentthread. name + currentthread. managedthreadid); myclass = new myclass (); threadstart start = new threadstart (myclass. dowork); thread = new thread (start); thread. isbackground = true; thread. start (); thread. sleep (1, 2000); console. writeline (currentthread. name + currentthread. managedthreadid );

 

 

 

This is the call code. As long as the foreground thread does not end, the background thread continues to execute. If we add the console. Readline (); Code at the end, the background thread will always run.

 

This article is over. Next we will learn about the concept of synchronous domain and context.

 

 

 

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.