Multithreaded Essay II (TASK)

Source: Internet
Author: User

The task class is the newly added feature of. NET 4.0, which further encapsulates the original Thread,threadpool, making multithreaded programming on the. NET platform more convenient. Don't say much nonsense, get to the point.

A. Task start

Task initiation is mainly used in the following ways:

1. Construct the Task object, start the task

1 New Task (dosomething); 2 Mytask.start ();

2. Start a task by task.factory

Task second = Task.Factory.StartNew (dosomething);

The difference is that when a task is created, it needs to start with the Start method, and the Task.factory StartNew method launches the task directly without having to start it manually.

Parameters are typically a delegate,action or lambda expression that tells the task what method to execute.

In addition, the task and task.factory have two versions with return values, which are used for tasks with return values, as follows:

New New MyClass ()); Mytask.start ();
New MyClass ());

Two. Task return value (the generic version has a return value)

You can get the return value in the following ways (note that this action will block the current thread):

var result = Mytask.result;

If you want to get the current state of the thread, you can call the task's status property, which is an enumeration value.

Three. Task End

If you need to manually control the end of a task, Microsoft provides the CancellationTokenSource token class, using the following methods:

New CancellationTokenSource (); TaskNew task<myclass> (() =>{thread.sleep ();  Returnnew  MyClass ();},canceltokensource.token); Mytask.start (); Canceltokensource.cancel () ;
New CancellationTokenSource (); Task<MyClass> mytask = Task.Factory.StartNew (() = {Thread.Sleep (  New  MyClass ();}, Canceltokensource.token); Canceltokensource.cancel ();

Ends the target task by the Cancel method.

The main points of the task are recorded here, and there is no shortage of places to add later.

Multithreaded Essay II (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: 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.