Task Parallel Library has a large codebase and some useful features such as Task.Unwrap
or Task.FromResult
that are not very well known to developers. We have still not mentioned two more extremely useful methods yet. They are covered in the following sections.
Often, it is required to wait for a certain amount of time in the code. One of the traditional ways to wait is using the Thread.Sleep
method. The problem is that Thread.Sleep
blocks the current thread, and it is not asynchronous.
Another disadvantage is that we cannot cancel waiting if something has happened. To implement a solution for this, we will have to use system synchronization primitives such as an event, but this is not very easy to code. To keep the code simple, we can use the Task.Delay
method:
// Do something await Task.Delay(1000); // Do something
This method can be canceled with a help of the CancellationToken
infrastructure and uses system timer under the hood, so this kind of waiting...