Task usage (1)-start method, task usage

Source: Internet
Author: User

Task usage (1)-start method, task usage
First, basically use Thread, ThreadPool, the difference between tasks is. added by NET4.0 is similar to the ThreadPool function of the Thread pool. When a Task is used to start a new Task, the Thread is called from the Thread pool, and a new Thread is created every time the Thread is instantiated. For a long operation, use Task (Acton, TaskCreationOptions) to construct TaskCreationOptions in the function. longRunning, indicating that the task scheduler places this thread on a non-thread pool to execute the second and fourth startup methods.1) start through start, a new 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 < 100; i++)            {                Console.WriteLine("i={0}\n", i);            }        }    }

  

2) Run directly through Run, and accept an Action as the parameter. The returned object is a Task.

 static void Main(string[] args)        {            Task.Run(() =>            {                for (int i = 0; i < 50; i++)                {                    Console.WriteLine("i={0}",i);                }            });            Console.ReadKey();        }

 

3) threads with return parameters

Task <int> task = Task. run <int> () => {int sum = 0; for (int I = 0; I <50; I ++) {sum + = 1 ;} return sum;}); int result = task. result; Console. writeLine ("Calculation result: {0}", result); // output 50 Console. readKey ();

 

4) use Task. Factory

  Task t = Task.Factory.StartNew(() =>              {                  for (int i = 0; i < 10; 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.