Because the current project has the knowledge of multithreading and concurrency, I plan to learn more about multithreading recently. The first article, starting from the most basic, is how to start a thread, how to start the thread, and how to block the thread. This article summarizes the following points.
Initial Impression of Multithreading
First, let's take a look at the relationship between Process, AppDomain of application domain, and Thread.
The following points can be summarized:
Use Cases of Multithreading
The following scenarios are summarized:
Thread startup, suspension, and Termination
. Net framework provides a Thread class to use multithreading. It is in the namespace System. Threading.
Enable Thread: Create a Thread Object, which is divided into non-Ginseng ThreadStart and ParameterizedThreadStart. The input parameter is of the Object type.
Foreground Thread and background Thread: Use Thread. by default, the Start () method starts a foreground thread. Generally, we set the newly started thread to a background thread, because our main thread does not need to wait for the execution of the foreground thread to complete.
Suspended Thread: Use Thread. the Sleep () method can suspend the main thread, but the system cannot predict the running time of the asynchronous thread (newly opened thread). Therefore, it is not scientific to use the Sleep () method to block the main thread. We usually use the Join () method of asynchronous threads to ensure that the main thread ends after the asynchronous thread ends.
Terminate a Thread: Use the Thread. Abort () method.
A simple multi-thread instance
The following uses a simple example to demonstrate how to use simple multithreading. The sample code is as follows.
Namespace ThreadDemo {class Program {static void Main (string [] args) {// Thread Fish = new fish () {Name = "yellow croaker "}; thread thread1 = new Thread () => {fish. move () ;}); thread1.IsBackground = true; thread1.Start (); Fish fish2 = new Fish {Name = "Sharks"}; Thread thread2 = new Thread (() ==>{ fish2.Move () ;}); thread2.IsBackground = true; thread2.Start (); Console. readKey () ;}//< summary> /// Fish // </summary> public class Fish {public string Name {get; set ;} public int Score {get; set;} public Fish () {} public void Move () {Console. writeLine (string. format ("{0} on a tour... ", Name ));}}}
The program runs as follows:
In the next article, I will summarize how to use the thread pool ThreadPool.