Unknown C # basics 3. Thread Analysis

Source: Internet
Author: User

The thread can make your project run more smoothly.

What is a thread?

A thread is the smallest unit of the program execution flow and a single sequential control flow in the program. Each program has at least one thread, that is, the program itself.

In C #, you can use the classes, interfaces, and methods provided by System. Threading to implement all operations on the thread.

Single-threaded operations

Imagine you go into a fast food restaurant and yell "come to Lanzhou ramen bowl", then sit at the dinner table and wait. when the cook heard your request, he began to cook Lanzhou ramen. theoretically, when you call it, the cook has already received the command.

The code can be used as follows:

 

Static void Main (string [] args)
{
String name = "Lanzhou ramen ";
Console. WriteLine ("laibowl" + name );
PlaceOrder (name );
Console. WriteLine ("sitting at the dinner table ....");
Console. Read ();
}
Static void PlaceOrder (string name)
{
Console. WriteLine ("start production" + name );
}
Run the program and you will find that the output result is:

According to the displayed results, the cook was very fast and started as soon as he heard the command. to make the simulation of this program more realistic, we can imagine that "my action" is a thread, while "cook ramen" is a thread. if we use threads for implementation, it will be a bit interesting:
Static void PlaceOrder (string name)
{
Thread thread1 = new Thread (new ThreadStart (Cooking ));
Thread1.Start ();
}
Static void Cooking ()
{
Console. Write ("start production ");
}

Run the program and you will find that the output result is:

 

This means that although the cook heard your voice, the way you sit at the dinner table is more reasonable before he starts to ramen?

We can also introduce the following parameters:


Static void PlaceOrder (string name)
{
Thread thread1 = new Thread (t => Cooking (name ));
Thread1.Start ();
}
Static void Cooking (string name)
{
Console. WriteLine ("start production" + name );
}

 

Note that the above parameter transfer method is only used for. net 3.5/4

 

Multithreading

If a hotel has multiple chefs and multiple people order meals at the same time, we can simulate the implementation as follows:



Static void Main (string [] args)
{
String name = "Lanzhou ramen ";
Int number = 5;
Console. WriteLine ("Lai" + number + "bowl" + name );
PlaceOrder (name, 5 );
Console. WriteLine ("sitting at the dinner table ....");
Console. Read ();
}
Static void PlaceOrder (string name, int number)
{

For (int I = 0; I <number; I ++)
{
Thread thread1 = new Thread (t => Cooking (name ));
Thread1.Start ();
}
}
Static void Cooking (string name)
{
Console. WriteLine ("start production" + name );
}

 

After running, the result shows:

 

Well, some chefs are still acting like robots. Let's give them some time to rest:

 


Static void Cooking (string name)
{
Thread. Sleep (10 );
Console. WriteLine ("start production" + name );
}

 

Run the program again and the result is:

 

Thread relevance and independence

The operations of threads are relatively independent and complete different tasks, but they share resources in the process.

Make an experiment:


Static void PlaceOrder (string name, int number)
{
Int [] array = new int [] {1000,500,300,500, 1 };
For (int I = 0; I <number; I ++)
{

Int time = array [I];
Thread thread1 = new Thread (t => Cooking (name, I, time ));
Thread1.Start ();
}
}
Static void Cooking (string name, int id, int time)
{
Thread. Sleep (10 );
Console. WriteLine (id + "starting to make" + name );
}

Here we want to give each cook a number, but when passing the parameters in I, visual studio will issue a warning:

"Access To Modified Closure".

What does this mean? Run the program and the output is:

 

 

It was found that the number of the cook was incorrectly read when the program was running, which is the cause of the warning: because the name I shared by the threads is constantly changing, we have no way to control the I values of a specific thread during runtime -- they are relatively independent.

The solution is to add a variable name to store the value as a pass:


static void PlaceOrder(string name, int number)
{
int[] array = new int[] {1000,500,300,500,1};
for (int i = 0; i < number; i++)
{
int j = i;
int time = array[i];
Thread thread1 = new Thread(t => Cooking(name, j,time));
thread1.Start();
}
}
Finally, let's take a look at the experiments that run independently in the thread:

Static void PlaceOrder (string name, int number)
{
Int [] array = new int [] {1000,500,300,500, 1 };
For (int I = 0; I <number; I ++)
{
Int j = I;
Int time = array [I];
Thread thread1 = new Thread (t => Cooking (name, j, time ));
Thread1.Start ();
}
}
Static void Cooking (string name, int id, int time)
{
Thread. Sleep (10 );
Console. WriteLine (id + "starting to make" + name );
Thread. Sleep (time );
Console. WriteLine (id + ", time spent:" + time );
}
The speed of each cook is different. They spend different time, so the first step is not necessarily done first. The result of running the above Code is:

 

Please read the above Code and output results carefully. You can understand them.

 

This article is from ASP. NET (Alex Song) of joy. Please indicate the source

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.