Cancel async tasks after a period of time (C#)

You can cancel an asynchronous operation after a period of time by using the CancellationTokenSource.CancelAfter method if you don't want to wait for the operation to finish. This method schedules the cancellation of any associated tasks that aren’t complete within the period of time that’s designated by the CancelAfter expression.

This example adds to the code that’s developed in Cancel an Async Task or a List of Tasks (C#) to download a list of websites and to display the length of the contents of each one.

Note

To run the examples, you must have Visual Studio 2012 or newer and the .NET Framework 4.5 or newer installed on your computer.

1. Decompress the file that you downloaded, and then start Visual Studio.

2. On the menu bar, choose File > Open > Project/Solution.

3. In the Open Project dialog box, open the folder that holds the sample code that you decompressed, and then open the solution (.sln) file for AsyncFineTuningCS.

4. In Solution Explorer, open the shortcut menu for the CancelAfterTime project, and then choose Set as StartUp Project.

5. Choose the F5 key to run the project. (Or, press Ctrl+F5 to run the project without debugging it).

6. Run the program several times to verify that the output might show output for all websites, no websites, or some web sites.

If you don't want to download the project, you can review the MainWindow.xaml.cs file at the end of this topic.

Build the example

The example in this topic adds to the project that's developed in Cancel an Async Task or a List of Tasks (C#) to cancel a list of tasks. The example uses the same UI, although the Cancel button isn’t used explicitly.

To specify a maximum time before the tasks are marked as canceled, add a call to CancelAfter to startButton_Click, as the following example shows. The addition is marked with asterisks.

private async void startButton_Click(object sender, RoutedEventArgs e)
{
// Instantiate the CancellationTokenSource.
cts = new CancellationTokenSource();

resultsTextBox.Clear();

try
{
// ***Set up the CancellationTokenSource to cancel after 2.5 seconds. (You
cts.CancelAfter(2500);

await AccessTheWebAsync(cts.Token);
}
catch (OperationCanceledException)
{
}
catch (Exception)
{
}

cts = null;
}


Run the program several times to verify that the output might show output for all websites, no websites, or some web sites. The following output is a sample.

Length of the downloaded string: 35990.



Complete example

The following code is the complete text of the MainWindow.xaml.cs file for the example. Asterisks mark the elements that were added for this example.

Notice that you must add a reference for System.Net.Http.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

// Add a using directive and a reference for System.Net.Http.
using System.Net.Http;

// Add the following using directive.

namespace CancelAfterTime
{
public partial class MainWindow : Window
{
CancellationTokenSource cts;

public MainWindow()
{
InitializeComponent();
}

private async void startButton_Click(object sender, RoutedEventArgs e)
{
// Instantiate the CancellationTokenSource.
cts = new CancellationTokenSource();

resultsTextBox.Clear();

try
{
// ***Set up the CancellationTokenSource to cancel after 2.5 seconds. (You
cts.CancelAfter(2500);

await AccessTheWebAsync(cts.Token);
}
catch (OperationCanceledException)
{
}
catch (Exception)
{
}

cts = null;
}

// You can still include a Cancel button if you want to.
private void cancelButton_Click(object sender, RoutedEventArgs e)
{
if (cts != null)
{
cts.Cancel();
}
}

{
// Declare an HttpClient object.
HttpClient client = new HttpClient();

// Make a list of web addresses.
List<string> urlList = SetUpURLList();

foreach (var url in urlList)
{
// Argument ct carries the message if the Cancel button is chosen.
HttpResponseMessage response = await client.GetAsync(url, ct);

// Retrieve the website contents from the HttpResponseMessage.

resultsTextBox.Text +=
}
}

private List<string> SetUpURLList()
{
List<string> urls = new List<string>
{
"https://msdn.microsoft.com",
"https://msdn.microsoft.com/library/windows/apps/br211380.aspx",
"https://msdn.microsoft.com/library/hh290136.aspx",
"https://msdn.microsoft.com/library/ee256749.aspx",
"https://msdn.microsoft.com/library/ms404677.aspx",
"https://msdn.microsoft.com/library/ff730837.aspx"
};
return urls;
}
}

// Sample Output: