Canceling asynchronous operations
In this section, we will look at how we can cancel long-running asynchronous operations. Sometimes a task will take longer than it should do. A good example of this is fetching data from a website when it goes down. Asynchronous operations can take a long time before they are reset by the server due to something like Error 404
, Error 401
, or Error 500
for example. And so, it pays to have the ability to cancel an asynchronous operation after a set period to prevent wasting an end user's time.
The code we will write will return the text from a website URL. We will assign a very short timeout. This timeout will cancel the task that is responsible for returning the website text. Follow these steps:
- Open the
CH16_AsynchronousProgramming
project, and add a new class calledTaskCancellation
. - Add the
using System.Text;
statement. - Add the following two member variables:
private const string _website = "https...