C # Task Usage

Source: Internet
Author: User

Tag: Eve false Load height enum returns set SetEvent comparison

Transfer from original C # Task usage

Use of C # Task

In fact, the Task is similar to the thread pool ThreadPool , but it is simpler and more intuitive to write. The code is more concise and uses Task to operate. You can control the execution of the method as easily as the thread.

By the way, with the CancellationTokenSource class, it is easier to terminate the execution of the Code of a task operation, as described in a later section.

If we use a thread pool to implement a few methods to run, and then wait for the run to finish, we will probably write the following code:

    using (ManualResetEvent m1 = new ManualResetEvent (false))    using (manualresetevent m2 = new ManualResetEvent (false)) c2/>{        ThreadPool.QueueUserWorkItem (delegate        {            Mymethoda ();            M1. Set ();        });        ThreadPool.QueueUserWorkItem (delegate        {            mymethodb ();            M2. Set ();        });        WaitHandle.WaitAll (New waithandle[] {m1, M2,});    }

If you use the Task class, it's relatively simple, at least the code looks comfortable. It also means that maintenance is more convenient.

    Task T1 = Task.Factory.StartNew (delegate  {Mymethoda ();});     = Task.Factory.StartNew (delegate  {mymethodb ();});    T1. Wait ();    T2. Wait ();

The above method is the execution of a one, get is not what we want, we generally want them to execute together at the same time, improve the efficiency of the program to deal with things.

    Task T1 = Task.Factory.StartNew (delegate  {Mymethoda ();});     = Task.Factory.StartNew (delegate  {mymethodb ();});    Task.waitall (t1, T2);

Let's briefly describe the use of the task below.

Create Task

There are two ways to create a Task, one to create using a constructor, and another to create it using TASK.FACTORY.STARTNEW. As shown in the following code

1. Creating a task using the constructor function

    1. task T1 = new task(MyMethod);

2. Create a task using Task.Factory.StartNew

    1. task T1 = task. Factory. StartNew(MyMethod);

In fact, both of these methods are the same, Task.factory is the Task of management, scheduling management this category. Studious partners can study in depth. This is not the scope of this article, perhaps in the following article to elaborate.

Run Task

There are two ways to run a task, as we mentioned above, one waiting to run and the other waiting for all of the running to complete. But here's another way to run asynchronous , just like using multithreading, calling the Start () method in a Task object . Take a look at the console example below. Simply wait and allwait words, just waiting. Rather than execution. So we also need to call the start () method

    Static voidMain (string[] args) {Task T1=NewTask (MyMethod); T1.        Start (); Console.WriteLine ("main thread code run end");    Console.ReadLine (); }         Static voidMyMethod () { for(inti =0; I <5; i++) {Console.WriteLine (DateTime.Now.ToString ()); Thread.Sleep ( +); }    }

Run effect

Because we didn't call wait, so it was executed asynchronously ~

Cancel Task

We began by describing the CancellationTokenSource object's cancellation of a task. Generally do not use this method, generally will normally exit the running code, such as the use of bool Isexit to carry out a control. Instead of forcing the interrupt code halfway.

You can refer to this article of mine: http://www.wxzzz.com/643.html

As for the CancellationTokenSource control task, the next article will carry out a detailed introduction.

Exception Handling for Task

Because the task is executed asynchronously, you can also understand that as with multithreading, specific error captures need to be captured by themselves. Interestingly, the exception to the task is also re-thrown into wait and allwait, and we can easily catch these exceptions. The following code

 static  void  Main (string  [] args) {Task T1  = new          Task (MyMethod); T1.        Start (); T1.        Wait (); Console.WriteLine (   main thread code run ends  Span style= "color: #800000;"        > " );    Console.ReadLine ();   static  void   MyMethod () { throw  new  Except Ion (  "    ); }

Run effect

Get the return value of a Task

First look at the code

    task<string" test ");    T1. Wait ();    Console.WriteLine (t1. Result);    Console.ReadLine ();

The return value can be any type, because it is a generic-or still very concise code.

C # Task Usage

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.