An interview scene a long time ago :

interviewer : Tell me about your right JavaScript Let's understand closure ?

I : Um. , It's usually the front-end engineer who writes JS, We usually just write back-end code .

interviewer : You're a back-end programmer , ok , Let me ask you about multithreading .

I : Generally, multithreading is not used .

interviewer :............................. ( The end of the interview )

Okay , After a laugh , Let's see Thread,ThreadPool,Task, async, await The basic use method .

1.Thread

 private static void Main(string[] args)
{
System.Console.WriteLine(" Main thread start ");
var thread = new Thread(new ThreadStart(ThreadTest));
thread.Start(); System.Console.WriteLine(" End of main thread ");
System.Console.ReadLine();
} private static void ThreadTest()
{
System.Console.WriteLine(" Start executing child threads .... ");
Thread.Sleep();
}

Execution results :

The above code , It should be easy for everyone to understand , adopt new Thread To create a child thread , then .Start() Start execution .

We F12 ThreadStart notice  public delegate void ThreadStart();   Is a delegate with no parameters and no return value , that , What if you want to execute a method with parameters in the thread ?

OK, Let's see Thread Constructor for

ParameterizedThreadStart What is it? ? It literally means with parameters ThreadStart, continue F12 Look at it

Sure enough, I can bring one object Parameters of .

Change the code just now :

 private static void Main(string[] args)
{
System.Console.WriteLine(" Main thread start ");
var thread = new Thread(new ParameterizedThreadStart(ThreadTest));
thread.Start(); System.Console.WriteLine(" End of main thread ");
System.Console.ReadLine();
} private static void ThreadTest(object p)
{
System.Console.WriteLine(" Start executing child threads .... Parameters :{0} ", p);
Thread.Sleep();

Execution results :

( Of course, it can also be used ThreadStart(()=>{ }) Direct use lambda How expressions work , No sample code will be written here  )

See the execution result above , Sub thread because Thread.Sleep(100) , So every time you print out the final result , Then you may wonder , If I want to wait for the child thread to finish executing , I'll execute the code behind the main thread , What do I do ?

 private static void Main(string[] args)
{
System.Console.WriteLine(" Main thread start ");
var thread = new Thread(new ParameterizedThreadStart(ThreadTest));
thread.Start();
thread.Join(); System.Console.WriteLine(" End of main thread ");
System.Console.ReadLine();
}
private static void ThreadTest(object p)
{
System.Console.WriteLine(" Start executing child threads .... Parameters :{0} ", p);
Thread.Sleep();
}

Look for the , Add this sentence  thread.Join() , Whatever he means , Let's look at the implementation results first !

OK, Do you understand Join() That's the meaning of ?

2.ThreadPool

Why Thread There will be more ThreadPool 了 ?

  If your code is designed for a lot of use Thread, Then it may exceed the maximum number of threads in the system and cause a crash , And every time you create and destroy a thread, it's also a waste of resources ,ThreadPool Can help you improve code efficiency and manage your threads .

This is not the point , Today's focus is on learning how to use it .

 private static void Main(string[] args)
{
System.Console.WriteLine(" Main thread start ");
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadTest), ); System.Console.WriteLine(" End of main thread ");
System.Console.ReadLine();
} private static void ThreadTest(object p)
{
System.Console.WriteLine(" Start executing child threads .... Parameters :{0} ", p);
Thread.Sleep();
}

Have a look first WaitCallback The definition of

A delegate with parameters , This requires its delegate method to have a object The parameters of .

ThreadPool Static class through QueueUserWorkItem() Method to drain the working function into the thread pool , It doesn't need us to take the initiative .Start(), So can he Join() 了 ?

Let's just click , It doesn't need you to do it manually Start either Join This way .

Okay , Simple learning Thread and ThreadPool after , We found that their constructors are all delegates without return values , If we want to get the return value of the method executed by the child thread in the main thread , What do I do ? Task Come on !

3.Task

 private static void Main(string[] args)
{
System.Console.WriteLine(" Main thread start ");
// new Task How it was created - With no arguments
//Task task = new Task(ThreadTest);
//task.Start(); // new Task How it was created - With parameters
//Task task=new Task(() => ThreadTest(10)); //Task.Factory How it was created - With no arguments
//Task task = Task.Factory.StartNew(ThreadTest);
//task.Start(); //Task.Factory How it was created - With parameters
//Task task = Task.Factory.StartNew(() => ThreadTest(10));
//task.Start(); Task task = Task.Run(() => ThreadTest());
//Task task = Task.Run(() => ThreadTest(10)); System.Console.WriteLine(" End of main thread ");
System.Console.ReadLine();

Task Three ways to create threads ,Task.Run() No manual operation required Start() . The other two methods are manual Start(). They didn't Join() Method , In its place Wait()

We use it Run() Methods as an example , see Task How to get the return value of a method .

 private static void Main(string[] args)
{
System.Console.WriteLine(" Main thread start "); Task<int> task = Task.Run(() => ThreadTest());
var result = task.Result; System.Console.WriteLine(" End of main thread ,result={0}", result);
System.Console.ReadLine();
} private static int ThreadTest(int i)
{
Thread.Sleep();
System.Console.WriteLine(" The child thread starts ");
return i * ;
}

Execution results :

adopt task.Result We got in the sub thread ThreadTest Return value of method . Did you notice , The main thread prints the final output after the execution of the sub thread ! task.Result In addition to getting the return value , Is it right? Wait() similar ?

See here , You'd think , What's the difference between starting another thread to run time-consuming tasks and our normal writing method ? Will it be much more efficient ? Let's test it !

Conventional methods :

 private static void Main(string[] args)
{
DateTime dt1 = DateTime.Now;
int count = ;
for (int i = ; i < ; i++)
{
Thread.Sleep();
count += i;
}
System.Console.WriteLine(" Execution completed , Time consuming =" + (DateTime.Now - dt1).TotalMilliseconds);
System.Console.ReadLine();
}

Task Method :

 private static void Main(string[] args)
{
DateTime dt1 = DateTime.Now;
Task<int> task = Task.Run(() =>
{
int count = ;
for (int i = ; i < ; i++)
{
Thread.Sleep();
count += i;
}
return count;
}); var result = task.Result; System.Console.WriteLine(" Execution completed , Time consuming =" + (DateTime.Now - dt1).TotalMilliseconds);
System.Console.ReadLine();
}

This is awkward , use Task On the contrary, it takes longer to execute !!!   Is it the wrong way to open it ?

4.async  await

async Is a keyword that modifies an asynchronous method . There are two return types (void perhaps Task<T>)

await Must be in async Modified asynchronous method ,await It must be followed by an asynchronous method or Task. Represents the result of waiting for the following method asynchronously .

1. return void How to use

 private static void Main(string[] args)
{
System.Console.WriteLine(" Main thread start ");
for (int i = ; i < ; i++)
{
ThreadTest(i);
}
System.Console.WriteLine(" Main thread execution completed ");
System.Console.ReadLine();
} private static async void ThreadTest(int i)
{
await Task.Run(() =>
{
Thread.Sleep();
System.Console.WriteLine(" The child thread starts ,i=" + i);
});
}

Execution results

2. return Task<T> How to use

 private static void Main(string[] args)
{
System.Console.WriteLine(" Main thread start ");
var task = ThreadTest();
System.Console.WriteLine(" Main thread execution completed ,result="+ task.Result);
System.Console.ReadLine();
}
private static async Task<int> ThreadTest()
{
var count = ;
await Task.Run(() =>
{
for (int i = ; i < ; i++)
{
Thread.Sleep();
count += i;
System.Console.WriteLine("count="+ count);
}
});
return count;
}

The return is Task<T>, So it's like getting its return value , Certainly through .Result 了 , We must have doubts , This way and write directly Task What's the difference? ? Just for convenience and beauty ?

Next, let's test the execution efficiency !

 private static void Main(string[] args)
{
DateTime dt1 = DateTime.Now;
var t = ThreadTest().Result;
System.Console.WriteLine(" Execution completed , Time consuming =" + (DateTime.Now - dt1).TotalMilliseconds + " count=" + t);
System.Console.ReadLine();
} private static async Task<int> ThreadTest()
{
var count = ;
await Task.Run(() =>
{
for (int i = ; i < ; i++)
{
Thread.Sleep();
count += i;
}
});
return count;
}

Execution efficiency is no different from before , I don't know if this test method is reasonable ? Kneel down and ask the gods to share their teachings !

That's it for today , About  async  await and Task difference ,async  await Thread blocking problem , I'll study it later .

========================================================================================================

Split line

========================================================================================================

After this blog was published yesterday , Receiving criticism and instruction from the great God , Thank you very much !

After reading this article , Then I saw the light . The article links :https://msdn.microsoft.com/zh-cn/magazine/jj991977.aspx

Analyze yesterday's test “ performance ” Wrong use of instance code for :

1. Blind use task.Result To get the final result , This causes the main thread to block , Waiting for the child thread to finish executing . Such a time difference doesn't make much sense .

2. It's all in one Task.Run() Simulate a time-consuming operation in , Internal circulation Thread.Sleep(10). This moves the time-consuming operation to a child thread , Even if it's fast, it's fast , It doesn't show the superiority of multithreading at all .

Here is the modified test code , I want to see others async await The performance of the program :

1. Ordinary Task, adopt task.Result Get the return value .

 private static void Main(string[] args)
{
DateTime dt1 = DateTime.Now; for (int i = ; i <= ; i++)
{
var re = Task.Run(() =>
{
Thread.Sleep();
return i;
}).Result; System.Console.WriteLine("result=" + re); if (i == )
System.Console.WriteLine(" Execution completed , Time consuming =" + (DateTime.Now - dt1).TotalMilliseconds);
}
System.Console.ReadLine();
}

2. Use async await

 private static void Main(string[] args)
{
DateTime dt1 = DateTime.Now; for (int i = ; i <= ; i++)
{
var task = ThreadTest(dt1, i);
} System.Console.ReadLine();
} private static async Task<int> ThreadTest(DateTime dt1, int i)
{
int re = await Task.Run(() =>
{
Thread.Sleep();
return i;
}); System.Console.WriteLine("result=" + re); if (i == )
System.Console.WriteLine(" Execution completed , Time consuming =" + (DateTime.Now - dt1).TotalMilliseconds); return re;
}

async await It really shows its performance .

summary :

1. Don't use... Blindly task.Result

2.async await The meaning of ( Or with Task The difference between ) It is to get the return value without blocking the thread .

Address of blog Park :http://www.cnblogs.com/struggle999/p/6933376.html

from Thread,ThreadPool,Task, To async await The basic use of reading more related articles

  1. Thread,ThreadPool,Task, To async await The basic usage and understanding of

    An interview scene a long time ago : interviewer : Tell me about your right JavaScript Let's understand closure ? I : Um. , It's usually the front-end engineer who writes JS, We usually just write back-end code . interviewer : You're a back-end programmer , ok , Let me ask you about multithreading . ...

  2. elementary analysis C# Medium Thread ThreadPool Task and async/await

    .net It's inevitable to deal with threads in a project , The goal is to achieve asynchronous . Concurrent . From the very beginning new Thread() introduction , To the later Task.Run(), It's in use today async/await But there are a lot of questions when we are young . Let's take a look ...

  3. C# in Thread,Task,Async/Await,IAsyncResult The things about !

    Speaking of asynchrony ,Thread,Task,async/await,IAsyncResult These things can't be bypassed , Let's talk about them one by one today 1. Threads (Thread) The meaning of multithreading is in an application , There are multiple executive departments ...

  4. C# in Thread,Task,Async/Await,IAsyncResult The things about ![ Reprint ]

    Speaking of asynchrony ,Thread,Task,async/await,IAsyncResult These things can't be bypassed , Let's talk about them one by one today 1. Threads (Thread) The meaning of multithreading is in an application , There are multiple executive departments ...

  5. C# in Thread,Task,Async/Await Asynchronous programming

    What is asynchronous Synchronous and asynchronous are mainly used to modify methods . When a method is called , The caller needs to wait for the method to finish executing and return to continue , We call this method synchronous : When a method is called, it immediately returns , And get a thread to execute the internal business of the method , transfer ...

  6. thread、Task、async &amp; await

    Study Jesse The article async & await The past and this life (Updated) And come Thread It's multithreading that we started with .new One Thread object , Pass the method in . Manual Start() just so so ...

  7. Thread,Task,async/await,IAsyncResult

    1. Threads (Thread) The meaning of multithreading is in an application , There are multiple execution parts that can be executed at the same time : For time-consuming operations ( for example io, Database operation ), Or wait for a response ( Such as WCF signal communication ) The operation of , You can turn on the background thread to execute , So Lord ...

  8. c# in @ The role of signs C# Replication through serialization Let's talk about concurrent programming in detail -TPL Big data DataTable To List Efficiency comparison 【 Reprint 】C# Tool class : Realize file operation File Tool class of Asynchronous multithreading Async .net Multithreading Thread ThreadPool Task .Net Reflective learning

    c# in @ The role of signs   Refer to the official Microsoft documentation - Special characters @, Address  https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/toke ...

  9. C# Multithreading and asynchrony ( Two )——Task and async/await Detailed explanation

    One . What is asynchronous Synchronous and asynchronous are mainly used to modify methods . When a method is called , The caller needs to wait for the method to finish executing and return to continue , We call this method synchronous : When a method is called, it immediately returns , And get a thread to execute the internal business of the method ...

Random recommendation

  1. 【Android Study 】 solve Eclipse AVD Open the slow question

    1. Check... When creating “Snapshot” 2. after Start Check the corresponding .

  2. Head First Design patterns --11 The proxy pattern

    The proxy pattern : Provide a avatar or placeholder for another object to control access to that object . Code : interface Boss { public void meeting(); } class BossImp implem ...

  3. jq The countdown to the auction

    1jq The effect code of // Global variables are used to store the current time var nows; function rightZeroStr(v) { ) { " + v; } return v + "&quo ...

  4. use Firefly Create the first project

    The original address :http://blog.csdn.net/uxqclm/article/details/10382097 After installation , stay python script It's in the bag firefly-admin Tools for ...

  5. Calling remote services using interfaces ------ Using dynamic invocation of services , Realization .net It's like Dubbo How to play .

    Distributed microservices are now the first of many corporate architectures , As far as I know , quite a lot java The company structure is Maven+Dubbo+Zookeeper On the basis of . Dubbo yes Alibaba Open source distributed service framework , Its biggest feature is to press ...

  6. ASP.NET The foundation HttpModule Study

    Recent learning WCF Knowledge about IIS Version knowledge , Right HttpContext,HttpModule,HttpHandler I don't know much about the content of , These three are also ASP.NET Relative basic content , Spend some time in the evening on ...

  7. Junit test Use

    1. Import maven rely on <dependency> <groupId>junit</groupId> <artifactId>junit</arti ...

  8. eclipse To configure freemarker,*.ftl file

    Personal test , Provide 2 Ways of planting , The results are all good : ----------------------------------------- 1. Download the plug-in directly . Just download FreeMarker The identification of Jar The bag will do :888 ...

  9. Windows Terminal tools _MobaXterm

    Preface Some people like small and beautiful tools , Some people like big integration tools . Here's an enhanced Windows Terminal tools MobaXterm, It provides all the important remote networking tools (SSH,X11,RDP,VNC,FTP,MOSH ..... ...

  10. 2018-2019-2 20175213 Experiment 1 《Java Familiarity with development environment 》 Experimental report

    The first part is the experimental requirements :1 establish “ My student number exp1” The catalog of 2 stay “ My student number exp1” Create under directory src,bin Such as catalog 3 javac,java Execution in “ My student number exp1” Catalog 4 Submit Linux or Window or ...