Because task is a core class of. NET 4 Parallel programming, and we are in the same class that we often deal with in parallel programming, it is necessary to have a thorough understanding of the task.
The previous article focused on how to create a task, and this article mainly describes how to cancel a task.
The main topics of this article are as follows:
1. Detect whether a task is canceled by polling
2. Use a delegate delegate to detect whether a task is canceled
3. Use wait handle also detect whether task is canceled
4. Cancel multiple tasks
5. Create a token for a grouped cancellation task
6. Determine if a task has been canceled
The theory of this article is not much, there are many examples of code.
A standardized operation in the TPL is "Cancel task". The reason that it is a standardized operation is actually to compare this operation with the traditional multithreaded programming.
In the previous multithreaded programming, we usually write some code ourselves to cancel the running of the thread. However, the cancellation method is built into the TPL of. NET 4, and perhaps we feel that the TPL does not need to have the code built in, because it is too simple. But this built-in approach not only cancels out the running task, but also reduces some of the risks that might arise when you cancel a running task, which we'll cover in more detail in subsequent articles.
Creating a canceled task typically takes the following steps:
A.A. Create an instance of System.Threading.CancellationTokenSource:
Create the cancellation token source
CancellationTokenSource Tokensource = new CancellationTokenSource ();
B.b. Get a System.Threading.CancellationToken through the Cancellationtokensource.token property:
CancellationToken token = Tokensource.token;
C. Create a new task or TASK<T>, and in the constructor pass in the action or action<object> delegate as the first argument, pass in the CancellationToken as the second argument:
Task task = new Task (new Action (printmessage), token);
D.d. Calls the task's start () method.