Talk about the C # multithreading stuff-Threading Basics

Source: Internet
Author: User
Tags finally block

When I first approached the concept of "threading", I thought it was difficult to understand, read a lot of books and took a long time to realize its true meaning. Now I have a beginner's mentality, I understand the "multithreading" described to everyone. This is a series of articles that show a complete display of basic thread-related concepts. Hope to help beginners.

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

First, the basic concept

What is a process?

When a program starts running, it is a process that includes the memory and system resources that are used by the programs and programs that are running. And a process is made up of multiple threads.

What is a thread?

A thread is a flow of execution in a program, each with its own proprietary register (stack pointers, program counters, and so on), but the code area is shared, meaning that different threads can execute the same function.

What is multithreading?

Multithreading refers to a program that contains multiple execution streams, in which multiple different threads can be run concurrently to perform different tasks, that is, allowing a single program to create multiple threads of parallel execution to accomplish their tasks.

Foreground thread background thread?

The main thread of the application and any threads explicitly created by constructing a thread object are the foreground threads by default. The opposite thread pool line Cheng is considered a background thread. Any thread that is created by the native code that enters the managed execution environment is also marked as a background thread.

The lifetime of the thread can be changed from the foreground to the background or from the background to the foreground at any time.

Foreground threads can block the end of an application. Until all foreground threads have terminated, the CLR can close the application (that is, unload the hosted application domain).

A background thread (sometimes called a daemon thread) is considered by the CLR to be a way to make sacrifices in program execution, which can be ignored at any time, even if the thread is doing some work at this time. Therefore, if all foreground threads are terminated, the background thread is automatically terminated when the application domain is unloaded.

Threads are lightweight processes. A common instance of using threads is the implementation of parallel programming in modern operating systems. Using threads saves CPU cycles and increases the efficiency of the application.

Second, the life cycle of the thread

The thread life cycle begins when an object of the System.Threading.Thread class is created, ending when the thread is terminated or when execution is complete.

Various states in the thread life cycle:

Not started: State when a thread instance is created but the Start method is not called (marks the thread as a state that can run, but the specific execution time is determined by the CPU. )。

Ready state: The condition when the thread is ready to run and wait for the CPU cycle.

Non-operational status: The following scenarios are not operational: (The Sleep method has been called, the Wait method has been called, blocked by I/O operation)

Death state: The condition when the thread has completed execution or has been aborted.

Third, thread

1. Main thread

The first thread to be executed in a process is called the main path

usingSystem;usingSystem.Threading;namespacethreading{classProgram {Static voidMain (string[] args) {Thread th=Thread.CurrentThread; Th. Name="Mainthread"; Console.WriteLine ("This is {0}", Th.            Name);        Console.readkey (); }    }}

Output: This is Mainthread

2. Creation of threads

usingSystem;usingSystem.Threading;namespacethreading{classProgram { Public Static voidThread1 () {Console.WriteLine ("Thread1 starts"); }         Public Static voidThread2 (Objectdata) {Console.WriteLine ("Thread2 starts,para:{0}", data.        ToString ()); }        Static voidMain (string[] args) {            varT1 =NewThread (THREAD1); T1.            Start (); vart2 =NewThread (THREAD2); T2. Start ("thread2");        Console.readkey (); }    }}

Input:

Thread1 starts

Thread2 starts,para:thread2

3. Thread Management

Sleep () hangs and abort () destroys threads

Aborts the thread at run time by throwing ThreadAbortException. This exception cannot be captured, and if there is a finally block, the control is sent to the finally block

usingSystem;usingSystem.Threading;namespacethreading{classProgram { Public Static voidThread1 () {Console.WriteLine ("Thread1 starts"); Console.WriteLine ("Thread1 Paused for 5 seconds"); Thread.Sleep ( the); Console.WriteLine ("Thread1 Resumes"); }        Static voidMain (string[] args) {            varT1 =NewThread (THREAD1); T1.            Start ();        Console.readkey (); }    }}
Thread hangs Code
usingSystem;usingSystem.Threading;namespacethreading{classProgram { Public Static voidThread1 () {Try{Console.WriteLine ("Thread1 starts");  for(inti =0; I <=Ten; i++) {Thread.Sleep ( -);                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 voidMain (string[] args) {            //Turn on child threads            varT1 =NewThread (THREAD1); T1.            Start (); //main thread hangs 2sThread.Sleep ( -); //terminating T1 Child threadst1.            Abort ();        Console.readkey (); }    }}
Thread Destruction Code

Destroying code Execution results:

Iv. thread Pool

In a multithreaded program, the thread spends most of its time waiting for an event to occur before it can be given a response we generally use the ThreadPool (thread pool) to solve, the line accesses tile is dormant, just periodically wake up we use the timer (timer) to solve.

Because of the cost of creating and destroying threads, excessive use of threads can cause memory resources to be wasted, and the concept of a thread pool is introduced for performance reasons. The thread pool maintains a request queue, the thread pool's code extracts the task from the queue, and then it is delegated to a thread pool for execution, and the threads are not destroyed immediately after execution, so that tasks can be performed in the background and the overhead of thread creation and destruction can be reduced. The thread pool thread Cheng is considered a background thread.

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

Code Show:

usingSystem;usingSystem.Threading;namespacethreading{classProgram { Public Static voidThread1 (Objectdata) {Console.WriteLine ("Thread1 = {0}", data.        ToString ()); }        Static voidMain (string[] args) {            //controlling the size of threads//The first parameter is: The maximum number of worker threads in a thread pool//The second parameter is: The maximum number of asynchronous I/O threads in the thread poolThreadpool.setmaxthreads (3,3);  for(inti =0; I <Ten; i++)            {                //ThreadPool is a static class without instantiation,//ThreadPool.QueueUserWorkItem (New WaitCallback (THREAD1), i);ThreadPool.QueueUserWorkItem (Thread1, i); } Console.WriteLine ("Thread1 Sleep"); Thread.Sleep (100000); Console.WriteLine ("Thread1 End");        Console.readkey (); }    }}

Operation Result:

But why the first output Thread1 sleep? Sometimes it's randomly output in the middle.

In fact, the thread pool startup and termination is not what our program can control, and after the thread pools are executed, there is no return value , we can use ManualResetEvent to notify one or more waiting threads that an event has occurred

The Modified code:

usingSystem;usingSystem.Threading;namespacethreading{classProgram {//creates a new ManualResetEvent object and initializes it to a signal-free State        Private StaticManualResetEvent MRE =NewManualResetEvent (false);  Public Static voidThread1 (Objectdata) {Console.WriteLine ("Thread1 = {0}", data.            ToString ()); if(Convert.ToInt32 (data) = =9) {mre.            Set (); }        }        Static voidMain (string[] args) {            //controlling the size of threads//The first parameter is: The maximum number of worker threads in a thread pool//The second parameter is: The maximum number of asynchronous I/O threads in the thread poolThreadpool.setmaxthreads (3,3);  for(inti =0; I <Ten; i++)            {                //ThreadPool is a static class without instantiation,//ThreadPool.QueueUserWorkItem (New WaitCallback (THREAD1), i);ThreadPool.QueueUserWorkItem (Thread1, i); }            //blocks the current thread until the current WaitHandle receives a signal. MRe. WaitOne (Timeout.infinite,true); Console.WriteLine ("Thread1 Sleep"); Thread.Sleep (100000); Console.WriteLine ("Thread1 End");        Console.readkey (); }    }}

Input Result:

OK, get it done.

Resources:

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

Benefits of Multithreading:

can improve CPU utilization. In multithreaded programs, when a thread has to wait, the CPU can run other threads instead of waiting, which greatly increases the efficiency of the program.

The disadvantage of Multithreading:

Threads are also programs, so threads need to consume memory, and more threads consume more memory;

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

Access to shared resources between threads affects each other, and the issue of competing shared resources must be resolved;

Too many threads can lead to too much control and can eventually cause many bugs;

Vi. attention of Canada

If this article is helpful to you, please click on " good text to top " and " Follow me " in the bottom right corner.

Talk about the C # multithreading stuff-Threading Basics

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.