Thread Pools and tasks

Source: Internet
Author: User

    1. thread Pool
    1. Thread Pool Basics
      • Creating threads and destroying threads is an expensive operation that takes a lot of time. Too many threads are also bad for performance because the operating system has to dispatch a running thread and perform a live-text switchover. to improve the situation, the CLR contains code to manage his own thread Pool. The thread pool is a collection of threads that your application can Use. An operation request queue is maintained internally by the thread Pool. When an application executes an asynchronous request operation, a record entry (entry) is appended to the queue of the thread Pool. The thread pool code extracts the record entry from this antagonism, distributing the record entry (dispatch) to a thread Pool. Threads are not destroyed when the thread pool finishes the Task. instead, the line routines back to the thread pool, where it enters the idle state and waits for another Request. Because the thread does not destroy itself, no additional performance loss is incurred;
    2. Let's show you how to invoke a method asynchronously as a thread pool
       public Static voidmainthreadpool () {console.writeline ("main thread asynchronous operation queue");            ThreadPool.QueueUserWorkItem (threadproc); Console.WriteLine ("the main thread does other work"); Thread.Sleep ( +);//Simulate other workConsole.WriteLine ("main thread Run end");        Console.ReadLine (); }        /// <summary>        ///the same callback method as the delegate WaitCallback signature/// </summary>        /// <param name= "stateInfo" >If you are using QueueUserWorkItem (waitcallback callBack), This parameter defaults to null</param>        Static voidThreadProc (Object StateInfo) {console.writeline ("thread pool worker thread execution back out"); Thread.Sleep ( +);//Simulate other work}

      Output:

  1. Task
    1. It is easy to use ThreadPool 's QueueUserWorkItem method to initiate an asynchronous compute throttling Operation. But this technique has many limitations. The biggest problem is that there is no built-in mechanism to let you know when the operation is complete, and there is no mechanism to get the return value when the operation is Complete. To overcome these limitations (and solve some other problems), Microsoft introduced the concept of a Task. Tasks are used by using the types in the System.Threading.Tasks namespace.
    2. Create a task
       public Static voidrungetstarttask () {//one way to create: through the constructor of a taskTask T1 =NewTask (Task1); //Creation Method Two: call StartNew through the task factory to create and enableTask t2 =Task.Factory.StartNew (Task2); Console.WriteLine ("T1 task start state: {0},t2 task status: {1}", t1. Status, t2.            Status); t1.            Start (); Console.WriteLine ("T1 task start status: {0},t2 task status: {1}", t1. Status, t2.                        Status);            Task.waitall (t1, t2); Console.WriteLine ("main thread execution complete"); Console.WriteLine ("T1 final status: {0},t2 final state: {1}", t1. Status, t2.            Status);        Console.ReadLine (); }         public Static voidTask1 () {thread.sleep ( +); Console.WriteLine ("Run Task1"); }         public Static voidTask2 () {thread.sleep ( -); Console.WriteLine ("Run Task2"); }

      Output

    3. Understanding task status and life cycle
      • The execution of a task instance depends on the underlying hardware and the resources available at run Time. therefore, after you have obtained any information about a task instance, the state may change because the state of the task instance is also changing at the same time. When a task reaches one of its 3 possible final, it can no longer go back to any previous State.
      • T initial state: The task instance has 3 possible initial states, detailing
      • Final State: next, The task instance can transition to the running state and eventually to a final State. If the task instance has associated subtasks, then the task cannot be considered complete and the task will be transformed into the Waitingforchildrentocomplete State. When the subtasks of a task instance are complete, the task enters one of 3 possible final States. Detailed description is as follows
    4. Cancel a task
      • If you want to interrupt the execution of a task instance, you can do so by canceling the token (cancellation token)
      • CancellationTokenSource is able to initialize canceled requests, while
    5.  public Static voidrungetstarttaskcancel () {varCTS =NewCancellationTokenSource (); varCT =Cts.            Token; varSW =stopwatch.startnew (); varT1 = Task.Factory.StartNew (() =Task1cancel (ct), ct); varT2 = Task.Factory.StartNew (() =Task2cancel (ct), ct); //main thread simulation 1 secondsThread.Sleep ( +); Cts.            Cancel (); Try            {                if(! Task.waitall (Newtask[] {t1, t2}, the) {console.writeline ("Task1cancel and Task2cancel more than 2 seconds to Complete."); Console.WriteLine ("T1 Status"+t1.                    Status.tostring ()); Console.WriteLine ("T2 Status"+t2.                    Status.tostring ());                Console.ReadLine ();            } console.readline (); }            Catch(aggregateexception Ex) {foreach(Exception innerexceptioninchEx.                    Innerexceptions) {debug.writeline (innerexception.tostring ()); Console.WriteLine ("exception Message:"+innerexception.tostring ()); }                if(t1. IsCanceled) {console.writeline ("T1 task Run Task1cancel canceled"); }                if(t1. IsCanceled) {console.writeline ("T2 task Run Task2cancel canceled"); } Console.WriteLine ("Time Consuming"+SW.                Elapsed.tostring ()); Console.WriteLine ("Complete");            Console.ReadLine (); }        }         public Static voidtask1cancel (cancellationtoken Ct) {ct.            Throwifcancellationrequested (); varSW =stopwatch.startnew (); Thread.Sleep ( +); Console.WriteLine ("Run Task1"); Console.WriteLine ("task1:"+SW.            Elapsed.tostring ()); Ct.        Throwifcancellationrequested (); }         public Static voidtask2cancel (cancellationtoken Ct) {ct.            Throwifcancellationrequested (); varSW =stopwatch.startnew (); Thread.Sleep ( -); Console.WriteLine ("Run Task2"); Console.WriteLine ("task2:"+SW.        Elapsed.tostring ()); }
    6. Get return value from task
      • currently, Our task instances do not have a return value, they all run some delegates that do not return a Value. As it begins, the task can have a return Value. By using an task<tresult> instance, where TResult is replaced with the return Type.
         public Static voidRungetstarttaskresult () {varT1 = Task.Factory.StartNew (() = GetTask1 ("Chengtian")); //wait for T1 to finisht1.            Wait (); varT2 = Task.Factory.StartNew (() =            {                 for(inti =0; I < t1. result.count; i++) {console.writeline (t1.                result[i]);            }            }); Console.WriteLine ("End");        Console.ReadLine (); }         public Staticlist<Char> GetTask1 (stringSs) {thread.sleep ( +); returnSS.        ToList (); }

        Output return value

    7. By continuing the concatenation task
      • Retrofit The example above to start the T2 task after the T1 task is completed
    8.  public Static voidrungetstarttaskcontinuewith () {varT1 = Task.Factory.StartNew (() = GetTask1 ("Chengtian")); varT2 = t1. ContinueWith (t =            {                 for(inti =0; I < t1. result.count; i++) {console.writeline (t1.                result[i]);            }            }); Console.WriteLine ("End");        Console.ReadLine (); }

      You can call the ContinueWith method on any task instance to create a Continuation.    You can also concatenate many tasks, and then wait for the last task (t2 in this instance) to Finish.              

Thread Pools and tasks

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.