One: The benefits of task
ThreadPool has a lot of advantages over thread, but there are some inconvenient uses on ThreadPool. Like what:
1:threadpool does not support interactive operations such as the cancellation, completion, or failure notification of threads;
2:threadpool does not support the sequence of thread execution;
In the past, if developers needed to do a lot of extra work to implement the above features, the FCL now provides a more powerful concept: Task. The task online pool is optimized based on and provides more APIs. In FCL4.0, if we were to write multithreaded programs, the task was obviously better than the traditional way.
The following is a simple example of a task:
Staticvoid Main (string[] args)
{
Task T =new task (() =
{
Console.WriteLine ("Task starts working ...");
Simulation work Process
Thread.Sleep (5000);
});
T.start ();
T.continuewith (Task) =
{
Console.WriteLine ("Task completed, the status of completion time is:");
Console.WriteLine ("Iscanceled={0}\tiscompleted={1}\tisfaulted={2}", Task. IsCanceled, Task. IsCompleted, Task. isfaulted);
});
Console.readkey ();
}
Second: The completion status of the task
Task tasks have properties that let us query the state of the task when it is completed:
1:iscanceled, because it was canceled and completed;
2:iscompleted, successfully completed;
3:isfaulted, completed because of an exception
It is important to note that the task does not provide a callback event to inform completion (like BackgroundWorker), which accomplishes a similar function by enabling a new task. The ContinueWith method can initiate a new task when a task is completed, which naturally supports the task's completion notification: We can get the result value of the original task in the new task.
The following is a slightly more complex example, while supporting the completion of notifications, cancellations, and get task return values and other functions:
Staticvoid Main (string[] args)
{
CancellationTokenSource CTS =new CancellationTokenSource ();
Task<int> T =new task<int> (() = ADD (cts. Token), CTS. Token);
T.start ();
T.continuewith (taskended);
Wait for any key to cancel the task
Console.readkey ();
Cts. Cancel ();
Console.readkey ();
}
Staticvoid taskended (task<int> Task)
{
Console.WriteLine ("Task completed, the status of completion time is:");
Console.WriteLine ("Iscanceled={0}\tiscompleted={1}\tisfaulted={2}", Task. IsCanceled, Task. IsCompleted, Task. isfaulted);
Console.WriteLine ("The return value of the task is: {0}", task.) Result);
}
Staticint Add (CancellationToken CT)
{
Console.WriteLine ("Task Begins ...");
int result = 0;
while (!CT. iscancellationrequested)
{
result++;
Thread.Sleep (1000);
}
return result;
}
When you press the keyboard for about 3 seconds after the task starts, you get the following output:
Task begins ...
The task is completed and the status of the completion time is:
Iscanceled=false iscompleted=true Isfaulted=false
The return value of the task is: 3
You may wonder, our task is to deal with cancel, why the completed state iscanceled that column or false. This is because in our work tasks, we handle the business logic of iscancellationrequested, and we do not process it through the throwifcancellationrequested method. If the latter approach is used, the following:
Staticvoid Main (string[] args)
{
CancellationTokenSource CTS =new CancellationTokenSource ();
Task<int> T =new task<int> (() = Addcanclebythrow (cts. Token), CTS. Token);
T.start ();
T.continuewith (Taskendedbycatch);
Wait for any key to cancel the task
Console.readkey ();
Cts. Cancel ();
Console.readkey ();
}
Staticvoid Taskendedbycatch (task<int> Task)
{
Console.WriteLine ("Task completed, the status of completion time is:");
Console.WriteLine ("Iscanceled={0}\tiscompleted={1}\tisfaulted={2}", Task. IsCanceled, Task. IsCompleted, Task. isfaulted);
Try
{
Console.WriteLine ("The return value of the task is: {0}", task.) Result);
}
catch (AggregateException e)
{
E.handle (ERR) = err is operationcanceledexception);
}
}
Staticint addcanclebythrow (CancellationToken CT)
{
Console.WriteLine ("Task Begins ...");
int result = 0;
while (true)
{
Ct. Throwifcancellationrequested ();
result++;
Thread.Sleep (1000);
}
return result;
}
Then the output is:
Task begins ...
The task is completed and the status of the completion time is:
Iscanceled=true iscompleted=true Isfaulted=false
In the method Taskendedbycatch of the task end evaluation, if the task is terminated by the Throwifcancellationrequested method, the result value of the task will throw an exception operationcanceledexception Instead of getting the result value before the exception is thrown. This means that the task is canceled by way of exception, so you can notice that the status iscancled is true in the output of the above code.
Again, we notice that the cancellation is implemented in an unusual way, and that the isfaulted state of an exception in the task is still equal to false. This is because throwifcancellationrequested is a method of type CancellationTokenSource for collaborative cancellation, and the CLR has handled it in a special way. The CLR knows the code that this line of program developers intentionally makes, so it is not considered an exception (it is understood to be canceled). To get a state where isfaulted equals true, we can modify the while loop to simulate an exception:
while (true)
{
Ct. Throwifcancellationrequested ();
if (Result ==5)
{
Thrownew Exception ("error");
}
result++;
Thread.Sleep (1000);
}
The output after the simulated exception is:
Task begins ...
The task is completed and the status of the completion time is:
Iscanceled=false iscompleted=true Isfaulted=true
Three: Mission factory
The task also supports the concept of a mission factory. The task factory supports the sharing of the same state between multiple tasks, such as canceling type CancellationTokenSource that can be shared. By using a task factory, you can cancel a set of tasks at the same time:
Staticvoid Main (string[] args)
{
CancellationTokenSource CTS =new CancellationTokenSource ();
Wait for any key to cancel the task
TaskFactory TaskFactory =new TaskFactory ();
task[] Tasks =new task[]
{
Taskfactory.startnew (() = ADD (cts. Token)),
Taskfactory.startnew (() = ADD (cts. Token)),
Taskfactory.startnew (() = ADD (cts. Token))
};
Cancellationtoken.none indicates that tasksended cannot be canceled
Taskfactory.continuewhenall (Tasks, tasksended, cancellationtoken.none);
Console.readkey ();
Cts. Cancel ();
Console.readkey ();
}
Staticvoid tasksended (task[] tasks)
{
Console.WriteLine ("All Tasks are complete! ");
}
The above code output is:
Task begins ...
Task begins ...
Task begins ...
All tasks have been completed (canceled)!
This recommendation shows how task (Task) and TaskFactory (Task Factory) are used. Task even further optimizes the scheduling of the background thread pool and speeds up the processing of threads. In the FCL4.0 era, using multi-threading, we were supposed to use task more.
Original: http://www.cnblogs.com/luminji/archive/2011/05/13/2044801.html
Recommendations for improving C # programs 9: Using task instead of ThreadPool and thread