Preface: Several previous articles have introduced the task's functions intermittently: Create, Cancel. This article describes the task of hibernation, the content of this article is relatively small.
The topics in this article are as follows:
1.Task of hibernation.
1.Task of hibernation
Sometimes, we often want a task to run after a period of time, a bit like sleep in multithreaded programming. We can set how long a task sleeps, and when that time is over, the task is automatically awakened and then run.
Now let's talk about the hibernation method:
A. Use CancellationToken's wait Handle:
A in. NET 4 parallel programming, the best way to hibernate a task is to use the CancellationToken wait operation (waiting Handle). And the operation is simple: first create an instance of CancellationTokenSource, and then get a CancellationToken instance from the token property of the instance, Then you use the CancellationToken WaitHandle attribute, and then call the WaitOne () method of this property. It has been used before in the article on "Cancellation of tasks".
b the WaitOne () method has a number of overloaded methods to provide more functionality, such as passing an integer to an int, indicating how long to hibernate, in microseconds, or passing in a TimeSpan value. If you call the CancellationToken Cancel () method, hibernation ends immediately. It is for this reason that our previous article has said that WaitOne () can be used as a solution to detect whether a task is canceled
Let's look at a sample code:
Code
static void Main (string[] args)
{
//Create the cancellation token source
CancellationTokenSource Tokensource = new CancellationTokenSource ();
//Create the cancellation token
CancellationToken token = tokensource.token;
Create the "the" which we'll let run fully
Task Task1 = new Task (() =>
{
for (int i = 0; i < Int32.MaxValue; i++)
{
// Put the task to sleep for seconds
BOOL cancelled = token. WaitHandle.WaitOne (10000);
//Print out a message
Console.WriteLine ("Task 1-int value {0}.") Cancelled? {1} ",
I, cancelled);
//Check to-if we have been cancelled
if (cancelled)
{
throw new OperationCanceledException (token);
}
}
}, token);
//Start Task
Task1. Start ();
//wait for input before exiting
Console.WriteLine ("Press ENTER to cancel token.");
Console.ReadLine ();
//Cancel the token
Tokensource.cancel ();
The wait for input before exiting the
Console.WriteLine ("Main method complete. Press ENTER to finish. ");
Console.ReadLine ();
}