Asynchronous thread Attachment Chapter

Source: Internet
Author: User

concurrency Programming knowledge in C #

Continue to the film, do further analysis, this article if there is a problem in the language, can be ignored

Thread section
         public class Testthread {public void Runthread () {//thread declaration thread when incoming method a,a can take parameter of type object, no return value,//If there is a parameter, start is enabled when it is passed in. The default is the foreground, which means that the end thread T1 = new Thread (() and {thread.sleep) after all threads have finished running.                                       (2000);                Console.WriteLine (222);                });                                      Thread t2 = new Thread ((object m) = = {Thread.Sleep (6000);                Console.WriteLine (m);                }); T2.                IsBackground = true; T2.                Start (333); T1.                Start ();                Thread.Sleep (1000);            Console.WriteLine (111);             } ######## Test part ######## testthread tw = new Testthread (); tw.                    Runthread (); Result: 111 222 CLR Auto-shutdown application 333 out of the analysis: Thread default is the foreground run, the foreground runs out of the CLR auto end (some not, for example, WInform is always running, if the console, such as Console.read (), keep the foreground waiting, is OK) T1 foreground run T2 background run, they and the main thread m parallel running m T2 T1                         stop 1s stop 2s stop 6s output 111 output 222--------------------------CLR End Output 333 ##########################//thread pool initialization execution method must take an object parameter//threadpool default with a parameter of object, no return value, the default is run in the background, that is, as long as the main thread is finished, the direct end, regardless of the child thread has not gone public void Runthreadpool () {Threadpool.que                    Ueuserworkitem (object o) = {Thread.Sleep (6000);                Console.WriteLine (222);                });                Thread.Sleep (1000);            Console.WriteLine (111);             } ######## Test part ######## testthread tw = new Testthread (); tw.                    Runthreadpool ();            Result: 111 CLR auto shutdown Application 222 out of the analysis: ThreadPool default is background run ########################## public void RunparaLler () {//parallel is a tool that executes loops with multiple threads//parallel is a normal sequential execution statement, just open multiple threads inside to run things, parallerl the following statements still need to wait para                int result = 0 To execute after execution of Llel;                int lockresult = 0;                Object lb = new object ();                    Parallel.For (0, 3, (i) = = {result = result + 2; Lock can only lock reference type, take advantage of the address of the reference object as a lock, implement the code in lock only one thread at a time access//lock let the code in lock become serial in parallel, try not to use lock in parallel (lock Operation time is small, lock outside operation is time consuming, parallel still works) lock (lb) {Lockresult = Lockresul                        T + 2;                        Thread.Sleep (2000);                    Console.WriteLine ("I={0},lockresult={1}", I, Lockresult);                } Console.WriteLine ("I={0},result={1}", I, result);                });            Console.WriteLine (11111);            } testthread tw = new Testthread (); tw.            Runparaller (); ######## Test Section######## Result: i=0,lockresult=2 i=0,result=6 i=1,lockresult=4 i= 1,result=6 i=2,lockresult=6 i=2,result=6 11111 Analysis: this                 A chestnut is a little special ah, if the cycle is large, the value of result does not know whether there is a problem ##########################}

As can be seen, thread multi-threading, passed in is not the return value of the method, does not involve the new thread return value of the discussion, the discussion is who first executed who finished after the impact of the final structure of the problem, the discussion domain is standing in a method, this method of new open thread discussion, Next we're going to switch to locating multi-threaded execution return values this block

Task

What is a task, what is its location in the thread, and why it is born, look at the following example

        public void Taskapply () {Console.WriteLine (1111);                  var t= task.run (() = {Thread.Sleep (8000);                             Console.WriteLine (5555);              });              Console.WriteLine (2222);              Thread.Sleep (1000);                                             Console.WriteLine (3333);         } ######## Test part ######## testtask tw = new Testtask (); tw.         Taskapply ();             Console.WriteLine (4444); Results: 1111 2222 (stop 1s) 3333 4444----CLR end 5555 and 6666 will not Out analysis: You can see the task is also running in the background of the thread, first encountered a task, the equivalent of a new run a isbackground to true thread, task.run inside also go, outside also go, parallel down Execution, outside of the 2222 output, stop a 1s, output 3333, the outside of the walk, continue to go outside the method, output 4444, the method is also gone, this time taskrun still in that sleep, regardless, the result came out ################# ######### from the above, as if he and isbackground=true the thread running characteristics like a very high, we smoothed, first thread is a front and back running, he passed the method can take an OBJect type parameter, can also without, no return value, two ThreadPool is must pass an object argument, is run in the background, there is no return value. But, task and they have some not fill in, task he passed the method can not take parameters, he is running in the background, the focus is can return value, we can move it to return the value of the place to get, the only thing to note is that when the acquisition will be blocked to the current thread, That is, the method in the task and the transfer of his into a string execution, of course, when the value of the call, may have been executed in the task is not good to say.             See the following changes to public void TaskApply2 () {Console.WriteLine (222);                  var t= task.run (() = {Thread.Sleep (8000);                  Console.WriteLine (555);              return 666;              });              Console.WriteLine (333);              Thread.Sleep (1000);              Console.WriteLine (444);              Console.WriteLine (T.result);                                             Console.WriteLine (777);         } ######## Test Part ######## Console.WriteLine (111);         Testtask tw = new Testtask (); tw.         Taskapply ();        Console.WriteLine (888); Results: 111 222 333 444 555 666 777 888 Analysis: the firstOutside the output 111, then into method B inside, output 222, and then encountered a Task, parallel started, outside (B) output 333, stop 1s, output 444, encountered T. Result, sorry, have to wait for the task to run down to execute, this time task.run inside of the 8s to the output 555, return the value back out, outside (b) Output 666, then output 777, the last outermost output 888 can be seen if the return value is not adjusted, outside (b            ) is not blocked waiting for the execution of Task.run inside, this is the task return value blocking characteristics

When we understand the above chestnut and analysis, we look at the following few simple is very fluent.

            public void Runbacktask () {Task t = new Task () = {                    Thread.Sleep (6000);                Console.WriteLine (333);                });                T.start ();                Console.WriteLine (111);                Thread.Sleep (2000);            Console.WriteLine (222);              }//Outside call Runbacktask This method when the first is output 111, stop a 2s, output 222,task 6s has not arrived, this time the outside to continue to run, this 333 output is going to look out of the outside and we have to look at the following only a ghost words                              public void Runtaskgui () {//111 222 333 444 555 666 sequential execution                    var ff = Task.run (() = {Thread.Sleep (6000);                    Console.WriteLine (111);                return 333; }).                Result;                Console.WriteLine (222);                Console.WriteLine (FF);                Thread.Sleep (6000);            Console.WriteLine (444);    } Outside of the tune Runtaskgui (), inside the order of the walk-through        According to this is 111 222 333 444, because Task.run () directly after the result, directly blocked, this method and the common method is the same              

From the above we found that we have been discussing how to invoke method a inside how to execute, the outside method must be called when method a straight line after the line, even if the call method A in the task of an asynchronous thread B, that is a new open parallel thread, Although this thread B does not block his statement below and our external method, we are also in the call method B to go to the last} and then straight out of our way

We are now going to switch to, tube you transfer method A inside to execute what east, I call you outside, I go directly below, seemingly outside another layer of asynchronous call

  public int SubTask () {thread.sleep (1000);                Console.WriteLine (333);                    var ff = Task.run (() = {Thread.Sleep (6000);                    Console.WriteLine (555);                return 666;                });                Console.WriteLine (444); Console.WriteLine (ff.               Result);            return 777;            } ######## Test Part ######## Console.WriteLine (111);                var s=task.run (() = {Testtask TM = new Testtask (); Return TM.                        SubTask ();            });            Console.WriteLine (222);            Console.WriteLine (S.result);                                         Console.WriteLine (888); Results: 111 222 333 444 555 666 777 8 88 I'm not going to explain this.  

Next look at another ghost Async + await

Async+await
             Public async void Runawaittask () {thread.sleep (1000);                Console.WriteLine (222);                    var ff= await Task.run (() = {Thread.Sleep (2000);                    Console.WriteLine (444);                return 666;                });                Console.WriteLine (555);                Console.WriteLine (FF);            Console.WriteLine (777);            } ######## Test part ######## testtask TM = new Testtask ();            Console.WriteLine (111); Tm.            Runawaittask ();            Console.WriteLine (333);            Thread.Sleep (6000);            Console.WriteLine (888);            Results: 111 222 333--the CLR may end after it's gone, so it doesn't have to be out there. 444 555 666            777//thread.sleep (6000);            Console.WriteLine (888);    After release, the result is: 111 222        333 444 555 666 777 888             

It is the most similar to the one we discussed above, look for, we found the goods, compared

        public void TaskApply2()        {             Console.WriteLine(222);             var t= Task.Run(() =>              {                  Thread.Sleep(8000);                  Console.WriteLine(555);                  return 666;              });              Console.WriteLine(333);              Thread.Sleep(1000);              Console.WriteLine(444);              Console.WriteLine(t.Result);              Console.WriteLine(777);                                             }         ######## 测试部分 ########         TestTask tw = new TestTask();         Console.WriteLine(111);         tw.TaskApply();         Console.WriteLine(888);         结果:        111        222         333        444        555        666        777        888                      

see similarities and differences point of no , see no , see No, see no , did not see the idea of the above task not set down

We found that calling an async method, when stepping into the inside step, encountered await, began to parallel, this parallel now becomes the outermost call method, rather than the inside of the statement

From the example, after the execution of Console.WriteLine (222), Runawaittask This encounter await and began to wait, await the following statement is blocked, and the outermost Console.WriteLine (333); You can go, In other words, the await task runs in parallel with the outermost one.

For TaskApply2, after encountering a task, the statement below the task Console.WriteLine (333); started executing, parallel is the following statement, not the outer Console.WriteLine (888); For Console.WriteLine (888), just after the TaskApply2 method is gone, if the Console.WriteLine (T.result) is removed, the result will be different, but the center difference has been found:

Async+await the point at which the concurrency begins is when an await is encountered and the outer layer is called in parallel with his task, and the outer statement begins to execute. The normal task is not related to the outer call, only the statement under the task is opened in parallel, and the outer layer is executed after the walk.

The above is just the introduction of async+await, they also have various restrictions and characteristics, such as:

The Async method return type is Task<t>,task, or void, so getting the return value can only be await or. Result, but Async+await and async+. The result is still different.

             public async void RunAwaitTask()            {                Thread.Sleep(1000);                Console.WriteLine(222);                var ff=Task.Run(() =>                {                    Thread.Sleep(2000);                    Console.WriteLine(444);                    return 666;                }).Result;                Console.WriteLine(555);                Console.WriteLine(ff);                Console.WriteLine(777);            }                  ######## 测试部分 ########        TestTask tm = new TestTask();        Console.WriteLine(111);        tm.RunAwaitTask();        Console.WriteLine(333);               结果:        111        222               444        555        666        777        333        可以看出关键点在于await        不解释了  

This is just the simplest start, and there are various asynchronous nesting. But the most basic difference in the mind must be fixed, so that encounter each scene can think of the version of the application and implementation, you can also determine how to write the code to go,. Threads are involved in threads that are executed in different time periods, and who executes them first, and who executes them all will result in different results. All have the guiding ideology to be able to diagnose slowly

Asynchronous thread Attachment Chapter

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.