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