Instance of Start method for Task Usage

Source: Internet
Author: User

First, basic use

The difference between the Thread,threadpool,task 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 the instantiation occurs. If this is a long operation, use the taskcreationoptions.longrunning in the task Acton,taskcreationoptions constructor to imply that the Task Scheduler is putting this thread on a non-threaded pool to execute

The second to fourth method of starting

1) Start with start, new a task, where the parameter is an action
Class program    {        static void Main (string[] args)        {            task t = new Task (DoA);            T.start ();            Console.readkey ();        }        static void DoA ()        {            for (int i = 0; i < i++)            {                Console.WriteLine ("i={0}\n", I);}        }    }

  

2) run directly by running, accept parameters an action, return object is a task

static void Main (string[] args)        {            task.run () =            {for                (int i = 0; i <; i++)                {                    CONSOLE.WR Iteline ("i={0}", i);                }            );            Console.readkey ();        }

3) thread with return parameters

   task<int> task = task.run<int> (() = =            {                int sum = 0;                for (int i = 0; i < i++)                {                    sum + = 1;                }                return sum;            });            int result = task. Result;            Console.WriteLine ("Result of operation: {0}", result);//output of            console.readkey ();

4) through Task.factory

  Task t = Task.Factory.StartNew (() =              {                  for (int i = 0; i <; i++)                  {                      Console.WriteLine ("I={0}", i);                  }              });

  

Related Article

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.