Windows-8.1

Cancelling an Async Task

Sometimes you may need to cancel a running asynchronous task, this following tutorial will show you how. Here’s how your task will work without an async cancellation.

Step 1: Create a new Windows Phone 8/8.1 Project

Start Visual Studio and create a new Windows Phone 8/8.1 project.

Step 2: In the MainPage.xaml paste the following code

Step 3: In the MainPage.xaml.cs above the constructor declare our CancellationTokenSource

 

CancellationTokenSource.Token property of cancellationToken is passed into our asynchronous task as an argument, while doing work the task can check the token to see if cancellation has been requested.

 

Step 4: Thereafter paste the following methods below the constructor


When the restart button is clicked, we cancel the current CancellationTokenSource which will stop the running task, we then instantiate a new CancellationTokenSource & start a new task. Here’s how it works,

Download the project source code and use it as a reference.

Download AsyncCancel.zip

LioneL Chetty

Microsoft Student Partner at the Durban University of Technology. I privately build Windows Phone applications & blog about my learning experiences.

Read more:
How to create your first Windows Phone app
How to change the App name and Tile name of your Windows phone app
Data binding in Windows Phone app – One way binding
Close