. NET parallel tasks-basic knowledge

Source: Internet
Author: User

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

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.