What's Thread,task,async/await,iasyncresult in C #!

Source: Internet
Author: User

Speaking of Async, thread,task,async/await,iasyncresult these things must not be around, and today we will talk about them in turn

1. Threads (thread)

The meaning of multithreading is that in an application, multiple execution parts can be executed concurrently, for more time-consuming operations (such as IO, database operations), or for operations that wait for a response (such as WCF communication) to be executed by opening a background thread independently so that the main thread is not blocked and can continue to execute Wait until the background thread finishes executing, then notifies the main thread, and then makes the corresponding operation!

Opening new threads in C # is easier

Static voidMain (string[] args) {Console.WriteLine ("Main thread Start"); //Isbackground=true, set it as a background threadThread T =NewThread (Run) {IsBackground =true }; T.start ();
Console.WriteLine ("The main thread is doing something else!") "); //The main thread ends, and the background threads end automatically, regardless of whether or not the execution is complete//Thread.Sleep (+);Thread.Sleep ( the); Console.WriteLine ("Main thread End");}Static voidRun () {Thread.Sleep ( the); Console.WriteLine ("This is a background thread call");}

Execution results such as,

You can see that after starting the background thread, the main thread continues to execute, and not wait until the background thread finishes executing.

1.1 Thread Pool

Imagine, if there are a lot of tasks to deal with, such as the site behind the HTTP request processing, it is not to create a background thread for each request? Obviously inappropriate, this consumes a lot of memory, and the process of creating frequently can seriously affect the speed. The thread pool is designed to solve this problem by saving the created threads into a thread pool (with multiple threads in it), and when the task is to be processed, if there are idle threads in the thread pool (the thread will not be recycled and will be set to idle when the previous task is completed), then the thread in the thread pool is directly invoked ( example, the Application object in the ASP. NET processing mechanism),

Use case:

 for (int0; i++) {    = =    {        Console.WriteLine ( Thread.CurrentThread.ManagedThreadId.ToString ());    });} Console.read ();

Operation Result:

You can see that, although it was executed 10 times, it did not create 10 threads.

1.2 Signal Volume (Semaphore)

Semaphore is responsible for coordinating threads and can limit the number of threads accessed for a resource

Here is a simple example of the use of the Semaphoreslim class:

StaticSemaphoreslim Semlim =NewSemaphoreslim (3); 3 indicates that only three threads can access at a timeStatic voidMain (string[] args) {     for(inti =0; I <Ten; i++)    {        NewThread (semaphoretest).    Start (); } console.read ();}Static voidsemaphoretest () {semlim.wait (); Console.WriteLine ("Threads"+ Thread.CurrentThread.ManagedThreadId.ToString () +"Start Execution"); Thread.Sleep ( -); Console.WriteLine ("Threads"+ Thread.CurrentThread.ManagedThreadId.ToString () +"execution Complete"); Semlim.release ();}

The results of the implementation are as follows:

As you can see, only three threads are executing at the beginning, and a new thread will execute the method after a thread has finished executing and releasing it!

In addition to the Semaphoreslim class, you can also use the semaphore class, feel more flexible, interesting words can search, here do not do a demonstration!

2.Task

The task is. NET4.0 joins, similar to the function of the thread pool ThreadPool, when a new task is opened with a task, the thread is called from the thread pool, and thread creates a new thread each time it instantiates.

Console.WriteLine ("Main thread Boot");//Task.run starting a thread//The task initiates a background thread, and to wait for the background thread to finish executing in the main thread, you can call the Wait method//Task task = Task.Factory.StartNew (() = {thread.sleep (1500); Console.WriteLine ("Task Start"); });Task task = Task.run (() = ={Thread.Sleep ( the); Console.WriteLine ("Task Start");}); Thread.Sleep ( -); task. Wait (); Console.WriteLine ("Main thread End");

The results of the implementation are as follows:

How to open a new task: Task.run () or Task.Factory.StartNew (), open a background thread

To wait for the background thread to finish executing in the main thread, you can use the Wait method (which executes synchronously). No wait is executed asynchronously.

Compare task and Thread:

Static voidMain (string[] args) {     for(inti =0; I <5; i++)    {        NewThread (RUN1).    Start (); }     for(inti =0; I <5; i++) {Task.run ()={Run2 ();}); }}Static voidRun1 () {Console.WriteLine ("Thread Id ="+Thread.CurrentThread.ManagedThreadId);}Static voidRun2 () {Console.WriteLine ("thread Id of the task call ="+Thread.CurrentThread.ManagedThreadId);}

Execution Result:

As can be seen, directly with thread will open 5 threads, with a task (using the thread pool) opened 3!

2.1 task<tresult>

Task<tresult> is the return value type, which is the Task,tresult with the return value.

 Console.WriteLine (  main thread start   "  //  Task<string  > Task = Task<string ;. Run (() => {Thread.Sleep ( 2000  );  return   Thread.CurrentThread.ManagedThreadId.ToString (); }); //  console.writeline (Task. Result); Console.WriteLine (   main thread end  ");

Operation Result:

Through task. Result can be taken to the return value, if the value of the time, the background thread has not finished, it will wait for the completion of its execution!

Simply mention:

Task tasks can be canceled by the CancellationTokenSource class, the feeling is not used much, the usage is relatively simple, interesting words can be searched!

3. async/await

Async/await is introduced in c#5.0, first use:

Static voidMain (string[] args) {Console.WriteLine ("-------Main thread start-------"); Task<int> task =Getstrlengthasync (); Console.WriteLine ("The main thread continues execution"); Console.WriteLine ("the value returned by the task"+task.    Result); Console.WriteLine ("-------Main thread end-------");}Static Asynctask<int>Getstrlengthasync () {Console.WriteLine ("Getstrlengthasync method starts execution"); //The string type in the <string> returned here, not task<string>    stringstr =awaitGetString (); Console.WriteLine ("Getstrlengthasync method Execution End"); returnStr. Length;}Statictask<string>GetString () {
   //console.writeline ("GetString method starts execution") returntask<string. Run (() ={Thread.Sleep ( -); return "return value of GetString"; });}

Async is used to modify the method to indicate that the method is asynchronous, and that the declared method must have a return type of: Void,task or task<tresult>.

An await must be used to decorate a task or task<tresult>, and only in an async method that is now decorated with the Async keyword. In general, async/await appear to be meaningful,

Look at the results of the operation:

As you can see, after the main function calls the Getstrlengthasync method, it is executed synchronously until the await keyword is encountered, and the main function returns to continue execution.

Does the program automatically open a background thread to execute the GetString method when it encounters the await keyword?

Now add that line of comments in the GetString method, and the result is:

As you can see, after encountering the await keyword, we did not proceed with the operation after the Getstrlengthasync method, and did not immediately return to the main function, but instead executed the first line of GetString. In this case, the await does not open a new thread to execute the GetString method, but instead synchronizes the GetString method to execute the Task<string> in the GetString method. Run (), the background thread was opened by task!

So what is the role of await?

Can literally understand that the above mentioned task.wait can let the main thread wait for the background thread to finish, await and wait similar, wait, wait for task<string> Run () begins the background thread execution, except that the await does not block the main thread and only causes the Getstrlengthasync method to pause execution.

So how is the await done? Have you opened a new thread to wait?

Only two threads (main thread and task open threads)! As to how to do it (I do not know ......>_<), everyone is interested in the study under it!

4.IAsyncResult

IAsyncResult since. NET1.1, a class that contains a method that is asynchronous can implement it, and the task class implements that interface

How to achieve asynchrony without the help of a task?

classprogram{Static voidMain (string[] args) {Console.WriteLine ("The main program starts--------------------"); intthreadId; Asyncdemo AD=NewAsyncdemo (); Asyncmethodcaller Caller=NewAsyncmethodcaller (AD.        TestMethod); IAsyncResult result = caller. BeginInvoke (3000,out threadId, NULL, NULL); Thread.Sleep (0); Console.WriteLine ("The main thread, {0}, is running.", Thread.CurrentThread.ManagedThreadId)//will block the thread until the background thread finishes executing result.        Asyncwaithandle.waitone (); Console.WriteLine ("The main program is doing some things!!! "); //get the results of an asynchronous execution        String returnvalue = caller.        EndInvoke (out threadId, result); //Freeing Resourcesresult. Asyncwaithandle.close ();Console.WriteLine ("Main program End--------------------");    Console.read (); }} Public classasyncdemo{//methods for the background thread to execute     Public stringTestMethod (intCallduration, out intthreadId) {Console.WriteLine ("The test method begins execution.");        Thread.Sleep (callduration); ThreadId=Thread.CurrentThread.ManagedThreadId; returnString.Format ("test method execution time {0}.", callduration.tostring ()); }} Public Delegate stringAsyncmethodcaller (intCallduration, out intTHREADID);

The key step is the part of the red font that runs the result:

The difference between the usage and the task is not very great! Result. Asyncwaithandle.waitone () is similar to a task's wait.

5.Parallel

Finally, a simple way to turn on multithreading in a loop:

Stopwatch Watch1 =NewStopwatch (); Watch1. Start (); for(inti =1; I <=Ten; i++) {Console.Write (i+","); Thread.Sleep ( +);} Watch1. Stop (); Console.WriteLine (Watch1. Elapsed); Stopwatch WATCH2=NewStopwatch (); Watch2. Start ();//threads in the thread pool are calledParallel.For (1, One, i ={Console.WriteLine (i+", thread ID:"+Thread.CurrentThread.ManagedThreadId); Thread.Sleep ( +);}); Watch2. Stop (); Console.WriteLine (WATCH2. Elapsed);

Operation Result:

Cyclic list<t>:

list<int> list = new List<int> () {1, 2, 3, 4, 5, 6, 6, 7, 8, 9};
parallel.foreach<int> (list, n + ={ Console.WriteLine (n); Thread.Sleep (+);});

Execute action[] Array inside the method:

New action[] {    new Action (() ={       Console.WriteLine (" Method 1")     }    ),new Action (() ={       Console.WriteLine (" Method 2 " );   })}; Parallel.Invoke (actions);

Well, the above is the whole content, space and ability are limited, I hope to be useful to everyone!

What's Thread,task,async/await,iasyncresult in C #!

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.