In the Microsoft. NET Framework, tasks are implemented through the task class in the System.Threading.Tasks command space. Its static property, Task.factory, is an instance of the TaskFactory class that is used to create and dispatch new tasks.
Scheduling is an important aspect of parallel tasks. The new task does not necessarily start as a thread, but is placed in a work queue.
Sample code
There are two methods, Doleft ()
1 Public Static void Doleft () 2 {3 Thread.Sleep (10000); 4 Console.WriteLine (string" doleft is running! " )); 5 }
and Doright ()
1 Public Static void doright () 2 {3 Thread.Sleep (+); 4 Console.WriteLine (string" doright is running! " )); 5 }
Let's do these two tasks in parallel.
Parallel.Invoke Way
1 Static voidMain (string[] args)2 {3Stopwatch SW =NewStopwatch ();4 SW. Start ();5 6 Parallel.Invoke (Doleft, doright);7 8 SW. Stop ();9Console.WriteLine (string. Format ("total time {0} seconds", SW. Elapsed.totalseconds));Ten One Console.read (); A}
The result of the operation is:
The running results indicate that the Parallel.Invoke method creates new tasks and waits for them to complete.
Task.factory.startnew method
Call method changed to:
1 Static voidMain (string[] args)2 {3Stopwatch SW =NewStopwatch ();4 SW. Start ();5 6 varTask1 = Task.Factory.StartNew (doleft);//StartNew, create and start System.Threading.Tasks.Task7 varTask2 =Task.Factory.StartNew (doright);8 9 SW. Stop ();TenConsole.WriteLine (string. Format ("total time {0} seconds", SW. Elapsed.totalseconds)); One A Console.read (); -}
Operation Result:
As a result, the StartNew method of the TaskFactory class creates and dispatches a new task and does not wait for the task to be completed. Add Task.waitall to wait for all parallel task executions to complete.
1 task.waitall (Task1, Task2);
You can see that it is waiting for all tasks to complete.
. NET parallel tasks-basic knowledge