Multithreading (basic), multithreading (basic)

Source: Internet
Author: User

Multithreading (basic), multithreading (basic)

In the multi-threaded series of articles, we will introduce the multi-threaded knowledge in the C # language. In the multi-threaded (basic) article, we will learn the following knowledge points:

  • Create thread
  • Abort thread
  • Thread wait
  • Terminate thread
  • Determine the thread status
  • Thread priority
  • Foreground thread and background thread
  • Passing parameters to the thread
  • Use the lock keyword of C # to lock the thread
  • Use Monitor to lock a thread
  • Exception Handling

1. Create a thread

In the entire series of articles, we mainly use Visual Studio 2015 as the main tool for Thread Programming. To create and use a thread in C #, follow these steps:

1. Start Visual Studio 2016 and create a console application.

2. Make sure that the console program uses. NET Framework 4.6 or later. However, all examples in this article can work normally with lower versions.

3. Double-click the "Program. cs" file in the console application and write the following code:

 1 using System; 2 using System.Threading; 3 using static System.Console; 4  5 namespace Recipe01 6 { 7     class Program 8     { 9         static void PrintNumbers()10         {11             WriteLine("Starting...");12             for (int i = 1; i < 10; i++)13             {14                 WriteLine(i);15             }16         }17 18         static void Main(string[] args)19         {20             Thread t = new Thread(PrintNumbers);21             t.Start();22             PrintNumbers();23         }24     }25 }

4. Run the console application. The running effect may be different each time, as shown in:

At line 1 of code, we imported the System. Threading namespace, which contains all the types required for writing multi-threaded programs.

In the 3rd line of code, we use the using static feature of C #6.0. After using this feature, we can use System in the code. you do not need to specify the type name for static methods of the Console type.

In 9th ~ In 16 lines of code, we define a method named "PrintNumbers", which will be called in the "Main" method and thread.

At line 3 of the Code, we created a thread to run the "PrintNumbers" method. When we initialize a thread, the constructor of an instance entrusted by "ThreadStart" or "ParameterizedThreadStart" is passed to the thread.

At line 3 of code, we start the thread.

In the code of line 3, we call the "PrintNumbers" method in the "Main" method.

Ii. Abort a thread

In this section, we will let the thread wait for some time, during which the thread will not consume the operating system resources. The procedure is as follows:

1. Use Visual Studio 2015 to create a new console application.

2. Double-click to open the "Program. cs" file and write the code as follows:

 1 using System; 2 using System.Threading; 3 using static System.Console; 4 using static System.Threading.Thread; 5  6 namespace Recipe02 7 { 8     class Program 9     {10         static void PrintNumbers()11         {12             WriteLine("Starting...");13 14             for(int i = 1; i < 10; i++)15             {16                 WriteLine(i);17             }18         }19 20         static void PrintNumbersWithDelay()21         {22             WriteLine("Starting...");23 24             for(int i = 1; i < 10; i++)25             {26                 Sleep(TimeSpan.FromSeconds(2));27                 WriteLine(i);28             }29         }30 31         static void Main(string[] args)32         {33             Thread t = new Thread(PrintNumbersWithDelay);34             t.Start();35             PrintNumbers();36         }37     }38 }

3. Run the console application. The running effect may be different each time, as shown in:

In 20th ~ In 29 lines of code, we define a new method "PrintNumbersWithDelay", which will be run in the newly created thread. It should be noted that in the 26th line of code, we use the static method "Sleep" of the "Thread" class, which makes every loop wait 2 seconds for execution.

In the code of Row 3, we create a new thread to run the "PrintNumbersWithDelay" method.

Iii. Thread waiting

In this section, we will describe how to execute the remaining code after a Thread is executed. To do this, we cannot use Thread. sleep method, because we do not know the exact execution time of another thread. To make a thread wait for another thread to complete other tasks, you only need to write the code as follows:

1. Use Visual Studio 2015 to create a new console application.

2. Double-click to open the "Program. cs" file and write the following code:

 1 using System; 2 using System.Threading; 3 using static System.Console; 4 using static System.Threading.Thread; 5  6 namespace Recipe03 7 { 8     class Program 9     {10         static void PrintNumbersWithDelay()11         {12             WriteLine("Starting...");13 14             for(int i = 1; i < 10; i++)15             {16                 Sleep(TimeSpan.FromSeconds(2));17                 WriteLine(i);18             }19         }20 21         static void Main(string[] args)22         {23             WriteLine("Starting...");24             Thread t = new Thread(PrintNumbersWithDelay);25             t.Start();26             t.Join();27             WriteLine("Thread completed");28         }29     }30 }

3. Run the console application. The running effect is shown in:

In the code of line 3, we call "t. join "method. This method allows us to wait until thread t finishes executing and then execute the remaining code in the" Main "method. With this technology, we can synchronize the execution steps of two threads. The first Thread waits for the second Thread to complete the execution and then performs other work. During the waiting period of the first Thread, the first Thread is in the "bolcked" status, and we call the Thread. sleep is in the same status.

4. terminate a thread

This section describes how to terminate the execution of another thread. The procedure is as follows:

1. Use Visual Studio 2015 to create a new console application.

2. Double-click to open the "Program. cs" file and write the following code:

 1 using System; 2 using System.Threading; 3 using static System.Console; 4 using static System.Threading.Thread; 5  6 namespace Recipe04 7 { 8     class Program 9     {10         static void PrintNumbers()11         {12             WriteLine("Starting...");13 14             for (int i = 1; i < 10; i++)15             {16                 WriteLine(i);17             }18         }19 20         static void PrintNumbersWithDelay()21         {22             WriteLine("Starting...");23             for (int i = 1; i < 10; i++)24             {25                 Sleep(TimeSpan.FromSeconds(2));26                 WriteLine(i);27             }28         }29 30         static void Main(string[] args)31         {32             WriteLine("Starting program...");33             Thread t = new Thread(PrintNumbersWithDelay);34             t.Start();35             Thread.Sleep(TimeSpan.FromSeconds(6));36             t.Abort();37             WriteLine("A thread has been aborted");38             t = new Thread(PrintNumbers);39             t.Start();40             PrintNumbers();41         }42     }43 }

3. Run the console application. The running effect may be different each time, as shown in:

At line 1 of code, we call the "t. Abort" method to terminate the execution of a thread. When the Abort method is called, a "ThreadAbortException" exception will be injected to the target thread. This exception will lead to thread termination, which is a very dangerous operation, this exception may occur at any time and cause destruction of the entire application. Therefore, it is not recommended to use the Abort method to terminate the execution of a thread. We can provide the thread with a "CancellationToken" object to cancel the execution of a thread. This technology will be described later.

Not complete to be continued!

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.