About C # multithreading-thread Basics,

Source: Internet
Author: User
Tags finally block

About C # multithreading-thread Basics,

When I first came into contact with the concept of "Thread", I thought it was difficult to understand. I read many books and it took a long time to understand its true meaning. Now I will describe the "multithreading" that I understand as a beginner. This is a series of articles that fully demonstrate the basic concepts related to threads. Hope to help beginners.

If you are a master, please do not continue reading it, it will waste your precious time.

I. Basic Concepts

What is a process?

When a program starts to run, it is a process, including the memory and system resources used by the running programs and programs. A process is composed of multiple threads.

What is a thread?

A thread is an execution stream in a program. Each thread has its own proprietary register (Stack pointer, program counter, etc.), but the code zone is shared, that is, different threads can execute the same function.

What is multithreading?

Multithreading means that a program contains multiple execution streams, that is, a program can run multiple different threads to execute different tasks at the same time, that is to say, a single program is allowed to create multiple parallel threads to complete their respective tasks.

Foreground thread background thread?

The main Thread of the application and any Thread explicitly created by constructing a Thread object are foreground threads by default. On the contrary, the thread pool thread is a background thread by default. In addition, any thread created by the local code entering the Managed execution environment is marked as a background thread.

In the thread life cycle, you can change from foreground to background at any time, or from background to foreground.

The front-end thread can block the end of the application. The CLR can close the application (that is, uninstall the hosted application domain) until all foreground threads are terminated ).

Background threads (sometimes called daemon threads) are considered by CLR as a way of sacrificing program execution, that is, they may be ignored at any time (even if the thread is executing a job at this time. Therefore, if all foreground threads terminate, the background threads are automatically terminated when the application domain is detached.

 

A thread is a lightweight process. A common example of using threads is the implementation of parallel programming in modern operating systems. The use of threads saves the CPU cycle and improves the efficiency of applications.

Ii. Thread Lifecycle

The Thread life cycle starts when the System. Threading. Thread class object is created and ends when the Thread is terminated or execution is completed.

Various States in the thread life cycle:

Not started: status when the thread instance is created but the Start method is not called (mark the thread as a running state, but the execution time is determined by the cpu .).

Ready status: the status when the thread is ready to run and waiting for the CPU cycle.

Non-running status: in the following situations, the thread cannot run: (the Sleep method has been called, the Wait method has been called, and the I/O operation is blocked)

Death status: status when the thread has been executed or aborted.

Iii. threads

1. Main thread

The first thread to be executed in the process is called as the main thread.

using System;using System.Threading;namespace Threading{    class Program    {        static void Main(string[] args)        {            Thread th = Thread.CurrentThread;            th.Name = "MainThread";            Console.WriteLine("This is {0}", th.Name);            Console.ReadKey();        }    }}

Output: This is MainThread

2. Thread Creation

using System;using System.Threading;namespace Threading{    class Program    {        public static void Thread1()        {            Console.WriteLine("Thread1 starts");        }        public static void Thread2(object data)        {            Console.WriteLine("Thread2 starts,para:{0}", data.ToString());        }        static void Main(string[] args)        {            var t1 = new Thread(Thread1);            t1.Start();            var t2 = new Thread(Thread2);            t2.Start("thread2");            Console.ReadKey();        }    }}

Input:

Thread1 starts

Thread2 starts, para: thread2

3. Thread Management

Sleep () suspension and Abort () Destruction thread

Thread is aborted at runtime by throwing threadabortexception. This exception cannot be caught. If a finally block exists, the control will be sent to the finally block.

Using System; using System. threading; namespace Threading {class Program {public static void Thread1 () {Console. writeLine ("Thread1 starts"); Console. writeLine ("Thread1 Paused for 5 seconds"); Thread. sleep (1, 5000); Console. writeLine ("Thread1 resumes");} static void Main (string [] args) {var t1 = new Thread (Thread1); t1.Start (); Console. readKey ();}}}Thread suspension code using System; using System. threading; namespace Threading {class Program {public static void Thread1 () {try {Console. writeLine ("Thread1 starts"); for (int I = 0; I <= 10; I ++) {Thread. sleep (1, 500); Console. writeLine (I);} Console. writeLine ("Thread1 Completed");} catch (ThreadAbortException ex) {Console. writeLine ("Thread1 Abort Exception");} finally {Console. writeLine ("Couldn't catch the Thread1 Exception");} static void Main (string [] args) {// enable the subthread var t1 = new Thread (Thread1 ); t1.Start (); // The Master Thread hangs for 2 s. sleep (2000); // terminate t1.Abort (); Console. readKey ();}}}Thread destruction code

Destroy the code execution result:

4. Thread Pool

In multi-threaded programs, threads spend most of their time waiting for an event to respond. We generally use ThreadPool to solve this problem; the thread is usually in sleep state, but it is periodically awakened. We use Timer (Timer) to solve this problem.

Because thread creation and destruction require a certain amount of overhead, excessive use of threads will cause a waste of memory resources. For performance considerations, the concept of thread pool is introduced. The thread pool maintains a request queue. The code in the thread pool extracts tasks from the queue and delegates them to a thread in the thread pool for execution. The thread will not be destroyed immediately after execution, in this way, tasks can be executed in the background, and the overhead of thread creation and destruction can be reduced. The thread pool thread is a background thread by default.

The thread pool automatically manages the creation and destruction of thread threads.

Code display:

Using System; using System. threading; namespace Threading {class Program {public static void Thread1 (object data) {Console. writeLine ("Thread1 => {0}", data. toString ();} static void Main (string [] args) {// controls the number of threads. // The first parameter is: maximum number of auxiliary threads in the thread pool // The second parameter is: Maximum number of asynchronous I/O threads in the thread pool ThreadPool. setMaxThreads (3, 3); for (int I = 0; I <10; I ++) {// ThreadPool is a static class that does not need to be instantiated, // ThreadPool. queueUserWorkItem (new WaitCallback (Thread1), I); ThreadPool. queueUserWorkItem (Thread1, I);} Console. writeLine ("Thread1 sleep"); Thread. sleep (1, 100000); Console. writeLine ("Thread1 end"); Console. readKey ();}}}

Running result:

But why do I first output Thread1 sleep? What about random output in the middle?

In fact,The startup and termination of the thread pool are not controlled by our program. After the thread in the thread pool is executed, no return value is returned., We can use ManualResetEvent to notify one or more threads that are waiting for an event.

Modified code:

Using System; using System. threading; namespace Threading {class Program {// create a ManualResetEvent object and initialize it as a non-signal State private static ManualResetEvent mre = new ManualResetEvent (false); public static void Thread1 (object data) {Console. writeLine ("Thread1 => {0}", data. toString (); if (Convert. toInt32 (data) = 9) {mre. set () ;}} static void Main (string [] args) {// control the number of threads. // The first parameter is: maximum number of auxiliary threads in the thread pool // The second parameter is asynchronous in the thread pool. The maximum number of I/O threads ThreadPool. setMaxThreads (3, 3); for (int I = 0; I <10; I ++) {// ThreadPool is a static class that does not need to be instantiated, // ThreadPool. queueUserWorkItem (new WaitCallback (Thread1), I); ThreadPool. queueUserWorkItem (Thread1, I);} // stop the current thread until the current WaitHandle receives the signal. Mre. waitOne (Timeout. infinite, true); Console. writeLine ("Thread1 sleep"); Thread. sleep (1, 100000); Console. writeLine ("Thread1 end"); Console. readKey ();}}}

Input result:

OK.

References:

ThreadPool: https://msdn.microsoft.com/zh-cn/library/system.threading.threadpool.aspx#Y0

ManualResetEvent: https://msdn.microsoft.com/zh-cn/library/system.threading.manualresetevent.aspx

V. Summary

Advantages of multithreading:

CPU utilization can be improved. In a multi-threaded program, when a thread has to wait, the CPU can run other threads instead of waiting, which greatly improves the program efficiency.

 

Disadvantages of multithreading:

The thread is also a program, so the thread needs to occupy the memory. The more threads occupy the memory, the more;

Multithreading requires coordination and management, so it requires CPU time to track threads;

Inter-thread access to shared resources will affect each other, and the problem of competing to share resources must be solved;

Too many threads will lead to too complex control, which may lead to many bugs;

 

6. Add attention

If this article is helpful to you, click 【Good text to topAnd 【Follow me]

 

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.