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); } });