. Net4.0 Tasks (Task) [go]

Source: Internet
Author: User
Tags terminates

. Net4.0 Tasks (Task)

A task is a lightweight object that manages a parallel unit of work. It avoids starting a dedicated thread by using the CLR's thread pool, which can be used more efficiently. List of task-related classes under the System.Threading.Tasks namespace:

Class Role
Task Manage work Units
Task<tresult> Managing units of work with return values
TaskFactory Create a task
Taskfactory<tresult> Create a task or a continuation with the same return value
TaskScheduler Manage Task Scheduling
TaskCompletionSource Manually control task workflows

Tasks are used to perform work in parallel, taking full advantage of multicore: In fact, parallel and PLINQ are built on the structure of task parallelism.

The task provides a series of powerful features to manage the unit of work, including:

    • Coordinating task Scheduling
    • Establish a parent-child relationship that initiates a task from another task
    • Achieve cooperative cancellation (cooperative cancellation) mode
    • No signal waiting for the task
    • Additional continuation tasks (continuation)
    • Scheduling a continuation task based on multiple ancestor tasks
    • Passing exceptions to a parent, continuation, or task consumer

At the same time, the task implements a local work queue, which allows you to efficiently create a fast-performing subtask without suffering a competing cost in a single work queue. Task parallel libraries allow you to create hundreds of thousands of tasks with minimal effort, but if you want to create millions of tasks, you must split those tasks into larger units of work to maintain efficiency.

Create and start a task

There are two ways to create a task, one to create and start a task through the TaskFactory StartNew () method, another to call the task constructor to create, and then to start the task manually. It is important to note that the task is not executed immediately after it is started and is managed by the Task Scheduler (TaskScheduler).

  • The TaskFactory startnew () method creates an example of a task as follows://No return value
    Task.Factory.StartNew (()=> Console.WriteLine ( "task created!" // There is a return value
    var task Task.factory.startnew<string> (() Span style= "color: #000000;" >=> task created!< Span style= "color: #800000;" > ");
    Console.WriteLine (Task. Result)
  • The
  • invoke Start method starts manually with the following example: var task new Task<string> () =>< Span style= "color: #000000;" > task created!" );
    Task. Start (); // asynchronously executes
    console.writeline (Task. Result)
  • The example that calls the RunSynchronously method to start manually is as follows:var task = New task<string>(() = "Task created!" );
    Task. RunSynchronously (); // Synchronous execution
    Console.WriteLine (Task. Result);

You can also specify a task status parameter when creating a task, which can be accessed through the AsyncState property of the task. Example:

var task = Task.Factory.StartNew (state = "Hello " + State , "Mike ");
Console.WriteLine (Task. asyncstate);
Console.WriteLine (Task. Result);

You can also specify a task Creation option (TaskCreationOptions) with the following enumeration values: None,longrunning,preferfairness,attachedtoparent. The function of each enumeration value is explained below.

  • Longrunning: As the name implies is a long-running task, this option recommends that the Task Scheduler assign a dedicated thread to the task. The reason for this is that long-running tasks can block the task queue, causing those short tasks to remain out of execution. The longrunning is also suitable for those blocking tasks.
  • Preferfairness: Fairness First, this option recommends that the Task Scheduler schedule tasks as much as possible according to the start time of the task. However, it is often not possible to do so because it optimizes task scheduling using the local work-stealing queue (the native work-stealing queues). This optimization is useful for very small tasks.
  • Attachtoparent: attached to the parent task, this option is used to create a child task. To create a subtask example:The first way:
    var parent=Task.Factory.StartNew (()=
    {
    var nonchildtask=Task.Factory.StartNew (
    ()=Console.WriteLine ("I ' m not a child task.");
    var childtask = Task.Factory.StartNew (
    () => Console.WriteLine (" i ' m a child task. "),
    Taskcreationoptions.attachedtoparent);
    });
    Second way:
    Task parent=new Task (() =>
    {
    DoStep1 ();
    });
    Task task2 = parent. ContinueWith ((prevtask) =>
    {
    DoStep2 ();
    });
    Parent. Start ();
Task wait

The task can wait for the task to complete through the wait () member method or the result property.

When the result property is called, the following actions are performed:

    1. If the task is finished, return to the task result
    2. If the task has started, wait for the task to end
    3. If the task has not started executing, the task is executed on the current thread

The Task.waitany () static method waits for any one task to complete. Example:

var tasks= Newtask[3];
For(IntI= 0; I<Tasks. Length; I++)
{
IntTaskindex=I
Tasks[i]=Task.Factory.StartNew (()=
{
IntSeed=guid.newguid (). GetHashCode ();
int waitTime = new Random (seed). Next (ten );
Thread.Sleep (WaitTime);
Console.WriteLine ("task{0} finished", Taskindex);
});
}
Task.waitany (tasks);
Console.WriteLine (" completed Tasks ");

The Task.waitall () static method waits for all tasks to complete. Even if a task throws an exception does not terminate the wait, it throws a AggregateException exception after all tasks have been completed, which aggregates all the exceptions thrown by the task. Example:

var tasks= Newtask[3];
For(IntI= 0; I<Tasks. Length; I++)
{
IntTaskindex=I
Tasks[i]=Task.Factory.StartNew (()=>
{
int< Span style= "color: #000000;" > WaitTime = new Random (Guid.NewGuid (). GetHashCode ()). Next (10 100);
Thread.Sleep (waitTime);
Console.WriteLine ( "task{0} finished "});
}
Task.waitall (tasks);
Console.WriteLine ( " All Tasks completed "); Exception handling

An exception that is unhandled by the task terminates the application by default. It should be noted that an unhandled exception in the task does not immediately cause the application to terminate, the exception is deferred until the garbage collector reclaims the task and the Finalize method is called to terminate the program. If the exception property of the task is read, this action will prevent the subsequent application from terminating.
When the wait task finishes, all unhandled exceptions are passed to the caller.
The Wait () method Timeout exception must also be handled, otherwise the application terminates.
Unhandled exceptions in a subtask are bubbled to the parent task, and exceptions to the non-subtasks in the nested task are not passed to the previous level of the task and need to be handled separately, or the application terminates.

var task=Task.Factory.StartNew (()=
{
Task.Factory.StartNew (()= = { throw null;}, Taskcreationoptions.attachedtoparent);
Task.Factory.StartNew (() = { throw null;}, Taskcreationoptions.attachedtoparent);
Task.Factory.StartNew (() = { throw null;}, Taskcreationoptions.attachedtoparent);
});
Task. Wait ();

Taskscheduler.unobservedtaskexception static events provide a last resort to handle all unhandled exceptions. By handling this event, you do not have to terminate the application and replace it with your own exception handling logic.

Cancel a task

When you create a task, you can pass in a cancellation token (cancelationtoken) parameter so that you can safely cancel the task. Example:

var source= NewCancellationTokenSource ();
var token=Source. Token;
var task=Task.Factory.StartNew (()=
{
Console.WriteLine ("Task starting ...");
While(True)
{
Token. Throwifcancellationrequested ();
Console.WriteLine ("I ' m alive. {0}", DateTime.Now);
Thread.Sleep (1000);
}
},token);

Task.Factory.StartNew (()=
{
Thread.Sleep (4500);
Source. Cancel ();
});

Try
{
Task. Wait ();
Console.WriteLine ( "task stopped." );
}
catch (AggregateException e)
{
if (e.innerexception is OperationCanceledException)
{
Console.WriteLine ( "task Canceled. ");
}
else
{
Console.WriteLine ( "errors. ");
}
} /span>

Cancel the task by calling the Cancel () method of CancellationTokenSource, which does not immediately terminate the task until the next time the task is canceled by throwing OperationCanceledException terminate the task.

If you want to cancel a task by throwing a operationcanceledexception exception directly, you need to pass in the Cancelationtoken parameter in the task. Otherwise, the status of the task cannot be taskstatus.canceled and the onlyoncanceled continuation task is triggered.

In addition, cancellation tokens can be passed to the wait and Cancelandwait methods to cancel the wait.

. Net4.0 Tasks (Task) [go]

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.