. NET Task (Task)

Source: Internet
Author: User

1. Task (Tasks):

It is easy to invoke ThreadPool.QueueUserWorkItem to implement asynchronous operations, but this technique has many

. NET introduces task types to use tasks.

The following three methods are implemented asynchronously:

   Public Static void Method ()        {            = = Console.WriteLine (""))            ; // scheduling Tasks            with start () New Task (() = Console.WriteLine ("")). Start ();             // to dispatch a task            by using the Run method Task.run (() = Console.WriteLine (""));        

A. In order to create a task, you need to call the constructor and pass an Action or action<object> delegate. This delegate is the code action you want to perform.

B. If you call run, you can pass an action or fun<tresult> delegate. The two differences are that Aciton has no return value, fun has a return value

2. Wait for the task to complete and get the result:

  Public Static voidMethod2 () {//Create a tasktask<int> t =Newtask<int> (n = Sum (int) n),Ten); //Start a taskT.start (); //wait for the task to completet.wait (); //Get ResultsConsole.WriteLine ("Sum is:{0}", T.result); }        Private Static intSum (intN) {intsum =0;  for(; n >0; n--)            {                checked{Sum + =N;} }            returnsum; }

3. Cancel the task:

. NET Task (Task)

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.