Waiting for time to pass C#. NET

It can be useful to have a Task wait for a given period of time, for example, if you are periodically polling the status of something before continuing executing the Task. Making a Task wait like this is referred to as sleeping. You specify a period of time for the Task to sleep for, and it will wait until that period of time has elapsed, at which point the Task will wake up and continue execution.

Putting Tasks to Sleep

Putting Tasks to Sleep

Using a Cancellation Token Wait Handle
The best way to put Tasks to sleep is to use the wait handle of a CancellationToken, which you saw earlier in the “Cancelling Tasks” section. Create an instance of Cancellation Token Source, and read the Token property to obtain the CancellationToken instance. Use the WaitHandle property, and call the overloaded WaitOne() method. In the “Cancelling Tasks” section, you saw the version that takes no arguments, which causes the calling thread to wait until the CancellationTokenSource.Cancel() method is called. However, other overloads of this method allow you to specify a period to wait using either an Int32 or a TimeSpan. When you specify a time period, the WaitOne() method will put the task to sleep for the specific number of milliseconds or until the CancellationToken is cancelled, whichever happens first. Listing demonstrates how this works.

Putting a Task to Sleep

Listing creates a Task that prints out a message and then sleeps for 10 seconds using the WaitOne() method. If you run the code, the messages will be printed until you hit the return key, at which point the CancellationToken will be cancelled, causing the Task to wake up again. Remember, the WaitOne() method will wait until either the time specified has elapsed or the token has been cancelled, whichever happens first. The CancellationToken.WaitHandle.WaitOne() method returns true if the token has been cancelled and false if the time elapsed, causing the task has woken up because the time specified has elapsed.

This technique is preferred for putting tasks to sleep because of the immediate response to the token being cancelled.we will observe in a moment that this is an improvement over the classic threading model.

Using Classic Sleep
Because the TPL uses the classic .NET threading support behind the scenes, you can use the classic threading technique to put a Task to sleep. Call the static Thread.Sleep() method, and pass a time interval as an argument. Reworks the previous example to use this technique.

Sleeping Using Classic Threads

The key difference with this technique is that cancelling the token doesn’t immediately cancel the task, because the Thread.Sleep() method will block until the time specified has elapsed and only then check the cancellation status. In this simple example, this means that the task continues to exist, albeit asleep, for up to 10 seconds after the token has been cancelled.

Using Spin Waiting
The spin waiting technique is included in this chapter for completeness, but this technique is recommend against using it. When you use the other two sleep techniques, the thread that is performing your task gives up its turn in the schedule when its sleeping, so any other threads can have a turn. The scheduler, which is responsible for managing the threads running at any given time, has to do some work to determine which thread should go next and make it happen. You can avoid the scheduler having to do this work by using a technique called spin waiting: the thread doesn’t give up its turn; it just enters a very tight loop on the CPU. Listing demonstrates how to perform spin waiting by using the Thread.SpinWait() method.

Sleeping by Spin Waiting

The integer argument passed to the Thread.SpinWait() method is the number of times that the tight CPU loop should be performed, and the amount of time that this takes depends on the speed of your system. Spin waiting is most commonly used to acquire synchronization locks, which are described in the next chapter. The problem with spin waiting is that your task doesn’t stop using the CPU; it just burns a specified number of CPU cycles. This approach distorts the behavior of the scheduling process, and you can get some quite odd behaviors from an application if you use spin locks wrongly. My advice is to avoid spin locking, because it can cause a lot more problems than it solves. There are very few applications that cannot rely on the more robust and predictable sleep techniques

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

C#. NET Topics