C # Multithreading basics, suitable for beginners to understand

Source: Internet
Author: User

First, create a thread

Throughout the series, we primarily use visual Studio 2015 as the primary tool for threading programming. Creating and using threads in the C # language requires only the following steps to write:

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

2. Ensure that the console program uses the. NET Framework version 4.6 or later. However, all the examples in this article use a lower version to work correctly.

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

usingSystem; usingSystem.Threading; using StaticSystem.Console; namespaceRECIPE01 {classProgram {Static voidprintnumbers () {WriteLine ("starting ...");  for(inti =1; I <Ten; i++) {WriteLine (i); }         }          Static voidMain (string[] args) {Thread T=NewThread (printnumbers);             T.start ();         Printnumbers (); }     } }

At the 2nd line of code, we imported the System.Threading namespace, which contains all the types we need to write a multi-threaded program.

In line 3rd, we used the using static property of C # 6.0, which, after using this attribute, allows us to use the static method of the System.Console type without specifying its type name in the code.

At the 9th to 16th line of code, we define a method called "printnumbers" that will be invoked in the "Main" method and Thread.

In line 20th, we create a thread to run the "Printnumbers" method, and when we initialize a thread, an instance of a "ThreadStart" or "Parameterizedthreadstart" delegate is passed to the thread's construction method.

At the 21st line of code, we start the thread.

In the 22nd line of code, we call the "Printnumbers" method in the "Main" method.

4. Run the console application and run the effect (the effect may be different for each run) as shown in:

Second, abort the thread

In this section, we will let the thread wait for some time, and the thread will not consume the operating system's resources during the waiting period. The following steps are written:

1. Create a new console application using Visual Studio 2015.

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

usingSystem; usingSystem.Threading; using StaticSystem.Console; namespaceRECIPE01 {classProgram {Static voidprintnumbers () {WriteLine ("starting ...");  for(inti =1; I <Ten; i++) {WriteLine (i); }         }          Static voidMain (string[] args) {Thread T=NewThread (printnumbers);             T.start ();         Printnumbers (); }     } }

3. Run the console application and run the effect (the effect may be different for each run) as shown in:

Three, thread wait

In this section, we'll talk about how to execute the rest of the code after a thread has finished executing, and we can't use the Thread.Sleep method because we don't know the exact execution time of another thread. To have one thread wait for another thread to finish and then do other work, just follow these steps to write code:

1. Create a new console application using Visual Studio 2015.

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

usingSystem; usingSystem.Threading; using StaticSystem.Console; using StaticSystem.Threading.Thread; namespaceRecipe03 {classProgram {Static voidPrintnumberswithdelay () {WriteLine ("starting ...");  for(inti =1; I <Ten; i++) {Sleep (Timespan.fromseconds (2));             WriteLine (i); }         }         Static voidMain (string[] args) {WriteLine ("starting ..."); Thread T=NewThread (Printnumberswithdelay);             T.start ();             T.join (); WriteLine ("Thread completed"); }    }}

3. Run the console application and run the effect as shown:

In the 26th line of code, we call the "T.join" method in the "main" method, which allows us to wait for the thread T to finish executing before executing 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 finish, and then it does the other work, and the first thread waits for a state of "bolcked", the same as the state we call Thread.Sleep.

Iv. Terminating Threads

In this section, we will tell you how to terminate execution of another thread. The steps are as follows:

1. Create a new console application using Visual Studio 2015.

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

 usingSystem;usingSystem.Threading; using StaticSystem.Console; using StaticSystem.Threading.Thread; namespaceRECIPE04 {classProgram {Static voidprintnumbers () {WriteLine ("starting ...");  for(inti =1; I <Ten; i++) {WriteLine (i); }         }          Static voidPrintnumberswithdelay () {WriteLine ("starting ...");  for(inti =1; I <Ten; i++) {Sleep (Timespan.fromseconds (2));             WriteLine (i); }         }          Static voidMain (string[] args) {WriteLine ("Starting program ..."); Thread T=NewThread (Printnumberswithdelay);             T.start (); Thread.Sleep (Timespan.fromseconds (6));             T.abort (); WriteLine ("A thread has been aborted"); T=NewThread (printnumbers);             T.start ();         Printnumbers (); }     } }

3. Run the console application and run the effect (the effect may be different for each run) as shown in:

C # Multithreading basics, suitable for beginners to understand

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.